如何在python 3中组合文件-使用open()作为:不工作



我试图将所有.txt文件的内容合并到一个目录中,该目录比下面存储.py文件的目录高一级。

import os
def main():
# Get list of files stored in a dir above this .py's dir
folder = os.listdir("../notes")
# Merge the files
merge_files(folder)
def merge_files(folder):
# Create a list to store the names of the files
files_names = []
# Open output file in append mode
with open("merged_notes.txt", "a") as outfile:
# Iterate through the list of files
for file in folder:
# Add name of file to list
files_names.append(file)
print(files_names)
# Open input file in read mode
with open(file, "r") as infile:
# Read data from input file
data = infile.read()

# Write data to output file (file name, data, new line)
outfile.write(file)
outfile.write(data)
outfile.write("n")
# Return merged file
return "merged_notes.txt"
if __name__ == "__main__":
main()

我一直得到这个错误:

FileNotFoundError: [Errno 2]没有这样的文件或目录:' file bard Mar 30 2023,4 30 48 PM.txt'

然而,文件名保存在列表files_names中,这意味着for循环确实在"注释"中找到了该文件。目录中。我不明白为什么with open(file, 'r')没有。

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

在print(file_names)之后添加以下行:

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

并更改open()函数以接受file_path:

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

当你试图遍历文件夹时,你只得到文件名,但你没有提供文件存储的路径,这就是为什么它不工作,因为文件在不同的文件夹中,而不是根文件夹,你必须给出文件路径。

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

尝试使用pathlib,它会给你一些更自动的东西:


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

相关内容

最新更新