起初,这个脚本运行良好,但在它显示错误后,"[WinError 3] The system cannot find the path specified"没有更改脚本中的任何内容。
import os
paths = os.listdir(r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables')
def files_with_word(word:str, paths:list) -> str:
for path in paths:
with open(path, "r") as f:
if word in f.read():
yield path
for filepath in files_with_word("Admin", paths):
print(filepath)我尝试卸载所有python并用python 3.11 64 bit重新安装它仍然不能工作。
发布于 2022-11-22 05:20:12
你所面临的问题就像没有使用绝对路径。paths = os.listdir(r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables')只会得到一个没有路径信息的文件名列表。因此,如果您在同一目录中没有实际运行python文件,它将生成该文件未找到的错误。
在for循环中,我只是将源目录和文件名放在一起,以获得打开的完整路径。您还需要筛选出目录,因为当前代码还会尝试将目录作为文件打开并导致错误。
import os
src = r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables'
files = os.listdir(src)
# only get files. filter out directories
files = [f for f in files if os.path.isfile(src+'/'+f)]
def files_with_word(word:str, files:list) -> str:
for file in files:
# create full path to file
full_path = src + "\\" + file
#open using full path
print(full_path)
with open(full_path, "r") as f:
if word in f.read():
yield file
for filepath in files_with_word("Admin", files):
print(filepath)https://stackoverflow.com/questions/74521325
复制相似问题