相关疑难解决方法(0)

如何使用open with语句打开文件

我正在研究如何在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)

python io file-io file python-3.x

184
推荐指数
3
解决办法
53万
查看次数

Python open()给出IOError:Errno 2没有这样的文件或目录

出于某种原因,我的代码无法打开一个简单的文件:

这是代码:

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()的完整路径,似乎没有任何工作.

python file-io file filenotfoundexception file-not-found

56
推荐指数
3
解决办法
30万
查看次数