我想逐行读取文件,但忽略任何包含冒号(:)的文件。
我当前正在打开一个文件,读取它,并尝试打印它,然后最终将其放入新文件中。
def shoppinglist():
infile = open('filename.txt')
contents = infile.readline()
output = open('outputfilename.txt', 'w')
while ":" not in contents:
contents = infile.readline()
else:
contentstr = contents.split()
print(contentstr)
output.write(contents)
infile.close()
output.close()
就这样,一遍又一遍地重复一行。
答案 0 :(得分:0)
尝试:
def shoppinglist():
contents = ""
with open('filename.txt', 'r') as infile:
for line in infile.readlines():
if ":" not in line:
contents += line
with open('outputfilename.txt', 'w') as output_file:
output_file.write(contents)