At first this script run fine but after it show this error "[WinError 3] The system cannot find the path specified"
without changing anything in the script
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)
I try uninstall all python and reinstall with python 3.11 64 bit
it still not working
The issue you are having looks like it is with not using absolute paths. paths = os.listdir(r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables')
will just get a list of filenames with no path info. So if you are not actually running the python file while in the same directory it will produce that file not found error.
In the for loop I just ocncantenated the source directory and filename together to get the full path to open. You will also want to filter out directories since the current code would also try to open a directory as a file and cause an error.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.