繁体   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