2013-05-03 116 views
0

我剛剛開始使用Python編寫第一個合適的項目,該代碼片段存儲程序。 爲此,我需要先將多行寫入.txt文件,然後再讀取。我做了很多搜索,並發現了一些關於寫入文件的信息(這並沒有真正起作用)。我目前正在工作的是一個函數,它讀取多行輸入的每一行,並將其寫入列表中,然後將其寫入文件。我曾經想過,我只能從文本文件中讀取它,並將每行添加到列表中,然後使用while循環分別打印每行,但不幸的是這些行不起作用。 經過和做更多的研究,我決定在這裏問。這是代碼我目前:將多行寫入文件,然後用Python讀取它們

''' 
Project created to store useful code snippets, prehaps one day it will evolve 
into something goregous, but, for now it's just a simple archiver/library 
''' 

#!/usr/local/bin/python 

import sys, os, curses 

os.system("clear") 

Menu =""" 
       #----------- Main Menu ---------# 

       # 1. Create or edit a snippet # 
       # 2. Read a snippet   # 
       # 0. Quit      # 

       #-------------------------------# 
\n 
""" 

CreateMenu =""" 
     #-------------- Creation and deletion --------------# 

     # 1. Create a snippet        # 
     # 2. Edit a snippet        # 
     # 3. Delete a snippet (Will ask for validation) # 
     # 0. Go back          #   

     #---------------------------------------------------# 
\n 
""" 

ReadMenu=""" 
        #------ Read a snippet ------# 

        # 1. Enter Snippet name # 
        # 2. List alphabetically # 
        # 3. Extra     # 
        # 0. Go Back    # 

        #----------------------------# 

""" 

def readFileLoop(usrChoice, directory): 
    count = 0 

    if usrChoice == 'y' or 'n': 
     if usrChoice == 'y': 
      f = open(directory, 'r') 
      text = f.read() 
      f.close() 

      length = len(text) 
      print text 
      print length 

      raw_input('Enter to continue') 
      readMenu() 
      f.close() 
     elif choice == 'n': 
      readMenu() 



def raw_lines(prompt=''): 
    result = [] 
    getmore = True 
    while getmore: 
     line = raw_input(prompt) 
     if len(line) > 0: 
     result.append(line) 
     else: 
     getmore = False 
    result = str(result) 
    result.replace('[','').replace(']','') 
    return result 


def mainMenu(): 
    os.system("clear") 
    print Menu 
    choice = '' 
    choice = raw_input('--: ') 
    createLoop = True  

    if choice == '1': 
      return creationMenu() 

    elif choice == '2': 
     readMenu() 

    elif choice == '0': 
     os.system("clear") 
     sys.exit(0) 

def create(): 
     os.system("clear") 
     name = raw_input("Enter the file name: ") 
     dire = ('shelf/'+name+'.txt') 

     if os.path.exists(dire): 
      while os.path.exists(dire): 
       os.system("clear") 
       print("This snippet already exists") 
       name = raw_input("Enter a different name: ") 
       dire = ('shelf/'+name+'.txt') 

      print("File created\n") 
      f = open(dire, "w") 
      print("---------Paste code below---------\n") 
      text = raw_lines() 
      raw_input('\nEnter to write to file') 
      f.writelines(text) 
      f.close() 
      raw_input('\nSnippet successfully filled, enter to continue') 


     else: 
      print("File created") 
      f = open(dire, "w") 
      print("---------Paste code below---------\n") 
      text = raw_lines() 
      print text 
      raw_input('\nEnter to write to file') 
      f.writelines(text) 
      f.close() 
      raw_input('\nSnippet successfully filled, enter to continue') 

def readMenu(): 
    os.system("clear") 

    name = '' 
    dire = '' 

    print ReadMenu 
    choice = raw_input('--:') 

    if choice == '1': 
     os.system("clear") 
     name = raw_input ('Enter Snippet name: ') 
     dire = ('shelf/'+name+'.txt') 

     if os.path.exists(dire): 
      choice = '' 
      choice = raw_input('The Snippet exists! Open? (y/n)') 

      '''if not choice == 'y' or 'n': 
       while (choice != 'y') or (choice != 'n'): 
        choice = raw_input('Enter \'y\' or \'n\' to continue: ') 
        if choice == 'y' or 'n': 
         break''' 

      readFileLoop(choice, dire) 

     else: 
      raw_input('No snippet with that name exists. Enter to continue: ') #add options to retry, create snippet or go back 
      readMenu() 

    elif choice == '0': 
     os.system("clear") 
     print Menu 

def creationMenu():    ###### Menu to create, edit and delete a snippet ###### 
     os.system("clear") 

     print CreateMenu 
     choice = raw_input('--: ') 

     if choice == '1':    ### Create a snippet 
      os.system("clear") 
      print create() 
      print creationMenu() 

     elif choice == '2': 
      os.system("clear")   ### Edit a snippet 
      print ("teh editon staton") 
      raw_input() 
      print creationMenu() 

     elif choice == '3': 
      os.system("clear")   ### Delete a snippet 
      print ("Deletion staton") 
      raw_input() 
      print creationMenu() 

     elif choice == '0':    ### Go Back 
      os.system("clear") 



######## Main loop ####### 

running = True 

print ('Welcome to the code library, please don\'t disturb other readers!\n\n') 

while running: 
    mainMenu() 

######## Main loop ####### 

鉈;博士:需要寫和讀多行文本文件

+0

據我所知,你的代碼已經_does_讀取多行文本文件。 'f.read()'將整個文件讀入一個大字符串,充滿嵌入的換行符。我不明白爲什麼代碼的結構是這樣的,或者你爲什麼關閉文件兩次,或者其他各種各樣的事情,但是......究竟是什麼部分在這裏被破壞或丟失? – abarnert 2013-05-03 22:26:51

+0

另外:「我曾經想過,我只能從文本文件中讀取它,並將每行添加到列表中,然後使用while循環單獨打印每行,但不幸的是這種行不起作用。」這有點含糊,但聽起來像是應該起作用的東西。沒有看到你嘗試過的實際代碼,很難告訴你這個想法或實現有什麼問題。 – abarnert 2013-05-03 22:28:00

+0

@abarnert我遇到的問題是多行被存儲到文件的方式,它以列表格式存儲,例如['line1','line2','line3'],這使得難以閱讀多行因爲我無法將它作爲列表讀取,當我嘗試將所有存儲的字符串添加到一個列表項中時。我不知道我是否正確寫入文件。 – user2348424 2013-05-04 09:48:06

回答

1

說我遇到的問題是在多線存儲到文件的方式,它存儲在列表格式如['line1', 'line2', 'line3']這使其難以解讀爲多線,因爲我不能讓它成爲作爲列表閱讀,當我嘗試它將整個存儲的字符串添加到一個列表項。我不知道我是否正確寫入文件。

行,所以問題是用這個文件。你正確地閱讀它,它只是沒有你想要的數據。問題在於你的raw_lines函數。首先它在result變量中組裝一列行,這很好。然後它這樣做:

result = str(result) 
result.replace('[','').replace(']','') 

這裏有兩個小問題和一個大問題。

首先,replace

返回[S]串與串的所有出現由更換副本。

Python字符串是不可變的。他們的方法都沒有在原地改變它們;他們都會返回一個新的字符串。你對這個新字符串沒有做任何事情,所以這條線沒有任何作用。其次,如果要將字符串序列加入到字符串中,則不要通過在序列上調用str來完成該操作,然後嘗試解析該字符串。這就是join方法的用途。例如,如果您的線路已經以換行符結束,您需要''.join(result)。如果沒有,你想要像'\n'.join(result) + '\n'。你在做什麼有各種各樣的問題 - 你忘了刪除額外的逗號,你會刪除任何括號(或逗號,一旦你解決這個問題)在字符串本身等。

最後,你不應該首先要做到這一點。你想要返回的東西可以傳遞給writelines,其中:

將[s]字符串序列寫入文件。序列可以是任何可生成字符串的可迭代對象,通常是字符串列表。

你有一個字符串列表,這是writelines想要什麼。不要試圖將它們合併成一個字符串。如果你這樣做,它會運行,但它不會做正確的事情(因爲一個字符串本身就是一個1字符串的序列)。

所以,如果你只是完全刪除這兩行,你的代碼將幾乎工作。

但還有最後一個問題:raw_input

...讀取輸入線,將其轉換爲字符串(剝離一個換行符),並返回。

writelines

...不加行分隔符。

所以,你最終將所有的行連在一起。你需要換行符,但raw_input把它們扔掉。所以,你必須重新添加它們。你可以通過一個簡單的單行更改來解決這個問題:

result.append(line + '\n') 
0

爲了從文件中讀取多行,這是最容易使用readlines(),這將返回一個列表的文件中的所有行。讀取文件使用:

with open(directory, 'r') as f: 
    lines = f.readlines() 

而且寫出來的更改,請:

with open(directory, 'w') as f: 
    f.writelines(lines) 
+0

代碼是正確的,但是......使用'readlines()'並不是最簡單的,事實上,當人們教新手使用它時,它就是我的寵物。 90%的時間,你可以用'f'代替'f.readlines()'。當你不能的時候,原因是你明確需要一個'list'而不是任何可迭代的,在這種情況下使用'list(f)'可以使這個更清晰。 – abarnert 2013-05-03 22:24:09

+2

我不同意'list(f)'更清晰,否則我會這樣寫(特別是對新手來說)。使用'readlines()'使我更清楚發生了什麼事情,而不是簡單地說'list(f)',對於新來的人來說,我會假設他們是一樣的,但對編程來說不一定是新事物。 'list(f)'可能看起來更像Pythonic,但我認爲'readlines()'對於讀者來說更容易理解。顯然,兩者都會給出相同的結果,只是在閱讀代碼時更容易理解。 – 2013-05-03 23:11:32

+0

最大的問題不是'f.readlines()'與'list(f)',而是'f.readlines()'和'f'。每週至少有一個問題來自人們詢問爲什麼他們的程序不適用於大文件,或者爲什麼當他們嘗試使用'stdin'時它會永遠掛起,或者爲什麼即使在使用4個線程後,他們的IO限制程序花費99%的時間在1線程中,或... – abarnert 2013-05-03 23:16:27

-1
fileList = [line for line in open("file.txt")] 

雖然先前提到的成語會讀取文件的工作,我喜歡我的。它的簡短和重點。

+0

另外,它是一個'SyntaxError',因爲這不是列表解析的工作方式。而且,作爲額外的好處,如果你解決了這個問題,它會泄漏文件句柄(並且也是不可預知的 - 它可以在一個Python實現/平臺上工作,但不能在另一個上工作,或者在發佈版中工作,但不在調試器中工作,或...)。 – abarnert 2013-05-03 22:19:44

相關問題