您没有将文件的完整路径提供给open()
,只是它的名字——相对路径。
非绝对路径指定相对于当前的位置工作目录 https://en.wikipedia.org/wiki/Working_directory(CWD,参见os.getcwd https://docs.python.org/3/library/os.html#os.getcwd).
你必须要么os.path.join()
正确的目录路径,或者os.chdir()
到文件所在的目录。
另外,请记住os.path.abspath() https://docs.python.org/3/library/os.path.html#os.path.abspath无法仅通过文件名推断出文件的完整路径。如果给定的路径是相对的,它只会在其输入中添加当前工作目录的路径前缀。
看起来您忘记修改file_array
列表。要解决此问题,请将第一个循环更改为:
file_array = [os.path.join(prefix_path, name) for name in file_array]
让我重申一下。
您的代码中的这一行:
file_array = [os.path.abspath(f) for f in os.listdir(prefix_path) if f.endswith('.txt')]
是错的。它不会为您提供包含正确绝对路径的列表。你应该做的是:
import os
import glob
prefix_path = ("C:/Users/mpotd/Documents/GitHub/Python-Sample-"
"codes/Mayur_Python_code/Question/wx_data/")
target_path = open('MissingPrcpData.txt', 'w')
file_array = [f for f in os.listdir(prefix_path) if f.endswith('.txt')]
file_array.sort() # file is sorted list
file_array = [os.path.join(prefix_path, name) for name in file_array]
for filename in file_array:
log = open(filename, 'r')