Python 逐行读取文件,并在每个文件中添加新内容
我知道以前也有人问过类似的问题,但我是python新手,无法找到解决问题的方法: 我想做的是: 1.打开一个文件并逐行读取。(我已经做到了) 2.在每行后面添加新内容。(我想稍后将其与if语句结合使用,以便只编辑特定的行) 我的代码:Python 逐行读取文件,并在每个文件中添加新内容,python,Python,我知道以前也有人问过类似的问题,但我是python新手,无法找到解决问题的方法: 我想做的是: 1.打开一个文件并逐行读取。(我已经做到了) 2.在每行后面添加新内容。(我想稍后将其与if语句结合使用,以便只编辑特定的行) 我的代码: #!/usr/bin/python3.4 file = open('testfile', 'r+') readlinebyline = file.readline() for i in range(0, len(readlinebyline)): read
#!/usr/bin/python3.4
file = open('testfile', 'r+')
readlinebyline = file.readline()
for i in range(0, len(readlinebyline)):
readlinebyline.write(' ' + 'checked')
print('done')
我希望以后我的测试文件看起来像这样:
line1 checked
line2 checked
line3 checked
...
但实际上它看起来是这样的:
line1
line2
line3
checked checked checked
如何让程序在每行结束后停止,然后向其中添加新内容?您可以使用
readlines
with open('testfile', 'r') as file:
# read a list of lines into data
lines = file.readlines()
with open('testfile', 'w') as file:
for line in lines:
# do your checks on the line..
file.write(line.strip() + ' checked' )
print('done')
我建议逐行将文件写入一个新文件,然后将该新文件移动到原始文件,这将覆盖该文件:
import shutil
filename = '2017-11-02.txt'
temp_filename = 'new.txt'
with open(filename, 'r') as old, open(temp_filename, 'w') as new:
# Go line by line in the old file
for line in old:
# Write to the new file
new.write('%s %s\n' % (line.strip(),'checked'))
shutil.move(temp_filename, filename)
与此相关的回答是:您不是逐行阅读,而是一次阅读整个文件,而且,您提供的代码会产生几个错误。代码不会产生任何错误。很抱歉,我没有使用testfile.readlines()。我使用了testfile.readline()。如果这有区别的话。刚刚编辑过,是的。它会产生一个
NameError
,因为没有定义testfile
,即使定义了,那么对于范围(0,len(readlinebyline())中的i:
会抛出一个类型错误
,因为列表对象是不可调用的。即使不这样做,readlinebyline.write
也会抛出一个AttributeError
,因为列表对象没有write
属性。但基本上,如果您能够将整个文件读取到内存中,最简单的事情就是读取it全部输入内存(如您所做的列表),然后截断文件,然后按您的意愿编写。通过修改创建一个新文件几乎总是比试图修改您正在读取的文件更好。当然,一旦新文件关闭,您可以轻松地用它替换原始文件(如果您愿意)。这样做不仅更简单,而且更安全:如果您的当代码运行时,计算机崩溃或断电。您的数据不会被损坏。这回答了问题,但不会关闭文件,也不符合PEP8。最简单的解决方案。谢谢,这正是我需要的。它工作正常。但我不完全理解“line.strip('\n')”部分尚未完成。strip方法似乎删除了行中的特定字符。那么,在这种情况下,它是否会在每次迭代中删除空白?对不起,我仍然是一个noob。如果能给出答案,我们将不胜感激。我真的想了解这一点否,它只删除“\n”,即每行末尾的新行字符,因此您可以添加“检查”已在同一行中\n'删除。
testfile=open('uat_config.conf', 'r+')
readlinebyline=testfile.readlines()
for i in range(0, len(readlinebyline)):
testfile.write("CHECKED "+ str(readlinebyline[i]))
print('done')
with open('file.txt', 'r') as f:
content = f.readlines()
with open('file.txt', 'w') as f:
for line in content:
f.write(line.strip('\n') + ' checked\n')