为什么我不能用Python将列表的第一个元素写入文本文件?

2024-04-19 17:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的文本文件

Bruce
brucechungulloa@outlook.com

我用它来读取文本文件并将其导出到一个列表中

with open('info.txt') as f:
    info =  f.readlines()            
    for item in info:
        reportePaises = open('reportePaises.txt', 'w')
        reportePaises.write("%s\n" % item)

但是当我想将列表的元素(info)写入另一个文本文件时,只会写入info[1](邮件)

如何将整个列表写入文本文件?你知道吗


Tags: infotxtcom列表foraswithopen
3条回答

每次写入文件时,您都会以写模式打开文件,实际上会覆盖您写入的前一行。改为使用append模式a。你知道吗

reportePaises = open('reportePaises.txt', 'a')

编辑:或者,您可以只打开一次文件,而不是在各行之间循环,按如下方式编写整个内容:

with open('reportePaises.txt', 'w') as file:
    file.write(f.read())

您遇到了问题,因为每次打开带有'w'标志的文件时,都会在磁盘上覆盖它。所以,你每次都创建了一个新文件。你知道吗

您应该在with语句中只打开第二个文件一次:

with open('info.txt') as f, open('reportePaises.txt', 'w') as reportePaises:
    info =  f.readlines()            
    for item in info:
        reportePaises.write(item)

正如@Pynchia所建议的,最好不要使用.readlines(),而是直接在输入文件上循环。你知道吗

with open('info.txt') as f, open('reportePaises.txt', 'w') as reportePaises:          
    for item in f:
        reportePaises.write(item)

这样,您就不会通过将while文件保存到列表来在RAM中创建while文件的副本,如果文件很大(显然,使用的RAM更多),则可能会导致巨大的延迟。相反,您将输入文件视为迭代器,在每次迭代中直接从HDD读取下一行。你知道吗

你也不需要在每一行都加上'\n'(如果我测试正确的话)。新行已经在item中了。因此,您根本不需要使用字符串格式,只要reportePaises.write(item)。你知道吗

with open('data.csv') as f:
    with open('test2.txt', 'a') as wp:
        for item in f.readlines():
            wp.write("%s" % item)
        wp.write('\n') # adds a new line after the looping is done

这将给你:

Bruce

brucechungulloa@outlook.com

在两个文件中。你知道吗

相关问题 更多 >