我正在研究如何在Python中进行文件输入和输出.我编写了以下代码来读取文件中的名称列表(每行一个)到另一个文件,同时根据文件中的名称检查名称,并将文本附加到文件中的出现位置.代码有效.可以做得更好吗?
我想对with open(...输入和输出文件使用该语句,但无法看到它们在同一块中的含义,这意味着我需要将名称存储在临时位置.
def filter(txt, oldfile, newfile):
'''\
Read a list of names from a file line by line into an output file.
If a line begins with a particular name, insert a string of text
after the name before appending the line to the output file.
'''
outfile = open(newfile, 'w')
with open(oldfile, 'r', encoding='utf-8') as infile:
for line in infile:
if line.startswith(txt):
line = line[0:len(txt)] + ' - Truly a great person!\n'
outfile.write(line)
outfile.close()
return # …Run Code Online (Sandbox Code Playgroud) 出于某种原因,我的代码无法打开一个简单的文件:
这是代码:
file1 = open('recentlyUpdated.yaml')
Run Code Online (Sandbox Code Playgroud)
错误是:
IOError: [Errno 2] No such file or directory: 'recentlyUpdated.yaml'
Run Code Online (Sandbox Code Playgroud)
open()的完整路径,似乎没有任何工作.