我之前已经知道类似的东西,但我是python的新手,我无法找到解决问题的方法:
我想做的是: 1.打开文件并逐行阅读。 (我已经设法做到了) 2.在每行后添加新内容。 (我想稍后将它与if语句结合起来,以便只编辑特定的行)
我的代码:
QuerySheet
之后我希望我的testfile看起来像这样:
ThisWorkbook.Worksheets
但它看起来像这样:
Option Explicit
Private Sub Workbook_Open()
QuerySheet.Initialize
End Sub
如何让程序在每一行之后停止,然后添加新内容?
答案 0 :(得分:1)
您可以使用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')
答案 1 :(得分:0)
我建议逐行将文件写入新文件,然后将该新文件移动到将覆盖它的原始文件:
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)
我根据以下内容提出了一些相关的答案:https://stackoverflow.com/a/16604958/5971137
答案 2 :(得分:0)
testfile=open('uat_config.conf', 'r+')
readlinebyline=testfile.readlines()
for i in range(0, len(readlinebyline)):
testfile.write("CHECKED "+ str(readlinebyline[i]))
print('done')
答案 3 :(得分:0)
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')