没有这样的文件或目录:'results.txt'

No such file or directory: 'results.txt'

我正在尝试写入 txt 文件,但遇到以下错误消息:[Errno 2] 没有这样的文件或目录:'results.txt'。 results.csv 文件包含由管道分隔符分隔的数据。我可以知道出了什么问题以及如何解决这个问题吗?

results_path = "results.csv"
dest_path = "results.txt"

def row_count(results_path):
    return len(open(results_path).readlines())

def add_header_footer(results_path, dest_path, file_name, date_today):
    with open(results_path) as from_file, open(dest_path) as to_file:
        header = 'H|ABC|' + file_name + '|' + date_today + '\n'
        footer = 'E|' + str(row_count(results_path)) + '|\n' 

        to_file.write(header)
        shutil.copyfileobj(from_file, to_file)
        to_file.write(footer)

add_header_footer(results_path, dest_path, 'Results_Today', '20190818')

Python 可以找到你的文件 result_path.

尝试将您的 results_path 变量设置为 Absolute path

通常当您调用与您的 py 文件不在同一级别的文件时,会显示该错误消息。

希望对您有所帮助! :D

您应该使用 open 目标文件和 w+ 模式。它尝试写入文件,如果不存在,则创建文件。更改这部分代码,看看它是否有效。

open(dest_path, 'w+') as to_file

还有其他类似的方式,a+追加。阅读更多 here