【问题标题】:No such file or directory: 'results.txt' [duplicate]没有这样的文件或目录:'results.txt' [重复]
【发布时间】:2019-12-23 18:45:06
【问题描述】:

我正在尝试写入 txt 文件,但遇到以下错误消息:[Errno 2] No such file or directory: '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 file-io


    【解决方案1】:

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

    open(dest_path, 'w+') as to_file
    

    还有其他模式,如a+ 用于追加。阅读更多here

    【讨论】:

      【解决方案2】:

      Python 可以找到你的文件 result_path。

      尝试将 results_path 变量设置为 Absolute path

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

      希望这有帮助! :D

      【讨论】:

      • 那行是什么意思-with open(results_path) as from_file, open(dest_path) as to_file:?
      • 我的意思是你的变量。更新了我的答案。
      猜你喜欢
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 2021-07-10
      • 2018-04-13
      相关资源
      最近更新 更多