簡體   English   中英

使用 write() 時如何附加到文件的新行?

[英]How can I append to the new line of a file while using write()?

在 Python 中:假設我有一個循環,在每個循環中我生成一個具有以下格式的列表:['n1','n2','n3'] 在每個循環之后我想寫入附加生成的條目到一個文件(其中包含以前循環的所有輸出)。 我怎樣才能做到這一點?

另外,有沒有辦法制作一個列表,其條目是這個循環的輸出? 即 [[],[],[]] 其中每個內部 []=['n1','n2','n3] 等

將單個列表作為一行寫入文件

當然,您可以將其寫入文件中,將其轉換為字符串后:

with open('some_file.dat', 'w') as f:
    for x in xrange(10):  # assume 10 cycles
        line = []
        # ... (here is your code, appending data to line) ...
        f.write('%r\n' % line)  # here you write representation to separate line

一次寫入所有行

當談到你問題的第二部分時:

另外,有沒有辦法制作一個列表,其條目是這個循環的輸出? [[],[],[]]其中每個內部[] = ['n1','n2','n3']

它也很基本。 假設您想一次保存所有內容,只需編寫:

lines = []  # container for a list of lines
for x in xrange(10):  # assume 10 cycles
    line = []
    # ... (here is your code, appending data to line) ...
    lines.append('%r\n' % line)  # here you add line to the list of lines
# here "lines" is your list of cycle results
with open('some_file.dat', 'w') as f:
    f.writelines(lines)

將列表寫入文件的更好方法

根據您的需要,您可能應該使用一種更專業的格式,而不僅僅是文本文件。 您可以使用例如,而不是編寫列表表示(可以,但不理想)。 csv模塊(類似於 Excel 的電子表格): http : //docs.python.org/3.3/library/csv.html

f=open(file,'a')第一個參數是文件的路徑,第二個參數是模式,'a' 是追加,'w' 是寫入,'r' 是讀取,依此類推,我認為,你可以使用f.write(list+'\\n')在循環中寫一行,否則你可以使用f.writelines(list) ,它也起作用。

希望這可以幫到你:

lVals = []
with open(filename, 'a') as f:
    for x,y,z in zip(range(10), range(5, 15), range(10, 20)):
        lVals.append([x,y,z])
        f.write(str(lVals[-1]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM