I am trying to open the file from folder and read it but it’s not locating it. I am using Python3
Here is my code:
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 = [os.path.abspath(f) for f in os.listdir(prefix_path) if
f.endswith('.txt')]
file_array.sort() # file is sorted list
for f_obj in range(len(file_array)):
file = os.path.abspath(file_array[f_obj])
join_file = os.path.join(prefix_path, file) #whole file path
for filename in file_array:
log = open(filename, 'r')#<---- Error is here
Error: FileNotFoundError: [Errno 2] No such file or directory: 'USC00110072.txt'
Kenil Vasani
You are not giving the full path to a file to the
open()
, just its name.You would have to either
os.path.join()
correct directory path to it, oros.chdir()
to the directory that the files reside in.From your code I can deduce though, that you are forgetting to modify the the
file_array
list. To fix this, change the first loop to this:Also, remember that
os.path.abspath()
can’t deduce the full path to a file just by it’s name.Let me reiterate.
This line in your code:
is wrong. It will not give you a list with correct absolute paths. What you should’ve done is: