繁体   English   中英

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

[英]Why I can´t write the first element of a list into a text file in 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)

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

如何将整个列表写入文本文件?

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

这会给你:

布鲁斯

brucechungulloa@outlook.com

在这两个文件中。

您遇到了问题,因为每次打开带有'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)

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

你也(如果我做的测试正确)不需要在每一行附加'\\n' 换行符已经在item 因此,您根本不需要使用字符串格式,只需reportePaises.write(item)

每次写入文件时,您都以写入模式打开文件,从而有效地覆盖了您写入的前一行。 使用附加模式a代替。

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

编辑:或者,您可以打开文件一次,而不是遍历行,按如下方式编写整个内容:

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

在不打开输出文件的情况下一次又一次地尝试此操作。

with open('info.txt') as f:
    info =  f.readlines()            

with open('reportePaises.txt', 'w') as f1:
    for x in info:
        f1.write("%s\n" % x)

那可行。

这里有两个问题。 一种是您在循环内打开输出文件。 这意味着它被多次打开。 由于您还使用了“w”标志,这意味着每次打开文件时都会将其截断为零。 因此,您只能写入最后一行。

最好在循环外打开输出文件。 您甚至可以使用with块的外部。

您可以简单地尝试以下代码。 您的代码不起作用,因为您在 for 循环中添加了打开文件处理程序“reportPaises”。 您不需要一次又一次地打开文件处理程序。

尝试在 python shell 中逐行重新运行您的代码,因为调试代码中的错误非常容易。

下面的代码将工作

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

您不需要在输出行中添加 \\n,因为当您执行 readlines 时,\\n 字符会保留在信息列表文件中。 请看下面的观察。

试试下面

with open('something.txt') as f:
    info =  f.readlines()
print info

你会得到的输出是

['Bruce\n', 'brucechungulloa@outlook.com']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM