如何在Python 3中组合文件 – 使用`with open()`:无法正常工作

huangapple go评论86阅读模式
英文:

How to combine files in python 3 - with open() as: NOT working

问题

抱歉,你的代码中存在一些HTML转义字符,我将提供一个不含HTML转义字符的中文翻译:

我正在尝试将存储在位于比下面的.py文件所在目录的上一级目录中的所有.txt文件的内容合并在一起。

  1. import os
  2. def main():
  3. # 获取存储在此.py文件的上一级目录中的文件列表
  4. folder = os.listdir("../notes")
  5. # 合并这些文件
  6. merge_files(folder)
  7. def merge_files(folder):
  8. # 创建一个列表来存储文件名
  9. files_names = []
  10. # 以追加模式打开输出文件
  11. with open("merged_notes.txt", "a") as outfile:
  12. # 遍历文件列表
  13. for file in folder:
  14. # 将文件名添加到列表
  15. files_names.append(file)
  16. print(files_names)
  17. # 以读取模式打开输入文件
  18. with open(file, "r") as infile:
  19. # 从输入文件中读取数据
  20. data = infile.read()
  21. # 将数据写入输出文件(文件名、数据、换行符)
  22. outfile.write(file)
  23. outfile.write(data)
  24. outfile.write("\n")
  25. # 返回合并后的文件名
  26. return "merged_notes.txt"
  27. if __name__ == "__main__":
  28. main()

我一直收到这个错误:

FileNotFoundError: [Errno 2] No such file or directory: 'File bard Mar 30 2023, 4 30 48 PM.txt'

然而,文件名确实保存在files_names列表中,这意味着for循环确实在“notes”目录中找到了文件。我不明白为什么with open(file, 'r')不起作用。

英文:

I am trying to combine the content of all .txt files in a directory one level above the directory where the .py file below is stored.

  1. import os
  2. def main():
  3. # Get list of files stored in a dir above this .py's dir
  4. folder = os.listdir("../notes")
  5. # Merge the files
  6. merge_files(folder)
  7. def merge_files(folder):
  8. # Create a list to store the names of the files
  9. files_names = []
  10. # Open output file in append mode
  11. with open("merged_notes.txt", "a") as outfile:
  12. # Iterate through the list of files
  13. for file in folder:
  14. # Add name of file to list
  15. files_names.append(file)
  16. print(files_names)
  17. # Open input file in read mode
  18. with open(file, "r") as infile:
  19. # Read data from input file
  20. data = infile.read()
  21. # Write data to output file (file name, data, new line)
  22. outfile.write(file)
  23. outfile.write(data)
  24. outfile.write("\n")
  25. # Return merged file
  26. return "merged_notes.txt"
  27. if __name__ == "__main__":
  28. main()

I keep getting this error:

> FileNotFoundError: [Errno 2] No such file or directory: 'File bard Mar 30 2023, 4 30 48 PM.txt'

However, the file name is saved in the list files_names, which means the for loop does find the file in the "notes" directory. I don't understand why with open(file, 'r') doesn't.

答案1

得分: 1

当您尝试遍历文件夹时,您只获取到文件名,但没有提供文件存储的路径,这就是为什么它不起作用的原因,因为文件位于根文件夹以外的不同文件夹中,您必须提供文件路径。

英文:

When you are trying to loop through the folder you are getting only the file names, but you are not providing the path where the file is stored,that's why its not working as the files are in a different folder than the root folder,you have to give the file path.

答案2

得分: 1

os.listdir("../notes")获得的文件名是相对于../notes目录的,而不是当前目录。您需要使用正确的路径前缀文件名。

尝试使用pathlib,它提供了更多的自动功能:

  1. from pathlib import Path
  2. notes = Path("../notes").iterdir()
  3. for note in notes:
  4. with open(note) as f:
  5. data = f.read()
  6. print(data) # 文件的内容
英文:

The file names that you get from os.listdir("../notes") is relative to the ../notes directory, not the current directory. You need to prefix the file name with the correct path.

Try using pathlib, which gives you some more automatic stuff:

  1. from pathlib import Path
  2. notes = Pathlib("../notes").iterdir()
  3. for note in notes:
  4. with open(note) as f:
  5. data = f.read()
  6. print(data) # contents of the file

答案3

得分: 1

open()函数期望一个文件路径,但你的代码中file只是文件名,没有包含文件所在目录的路径。

print(file_names)后面添加以下行:

  1. file_path = os.path.join("../notes", file)

并将open()函数的参数更改为file_path

  1. with open(file_path, "r") as infile:
英文:

The open() function expects a file path, but file in your code is just the file name without path to directory where file is location.

Add the following line right after print(file_names):

file_path = os.path.join("../notes", file)

And change the open() funtion to take in file_path:

with open(file_path, "r") as infile:

huangapple
  • 本文由 发表于 2023年3月31日 23:34:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定