How to resolve FileNotFoundError: [Errno 2] No such file or directory: in Pandas?
Code:
import pandas as pd
import glob
output_path = r'C:\\Users\\windows\\Documents\\test\\'
txt_files=glob.glob1(output_path,'Region_*.txt')
for txt_file in txt_files:
print(txt_file) # here output is received as Region_CAN.txt
df1 = pd.DataFrame()
df1 = pd.read_csv(txt_file,sep='\t')
print(df1)
output is received for print(txt_file)
however it cannot read the txt_file.
Error:
FileNotFoundError: [Errno 2] No such file or directory: 'Region_CAN.txt'
Solution 1:
glob.glob1(dirname, pattern)
method only returns the filenames. You need to provide the full path of txt file to pd.read_csv()
.
You can do with glob.glob(pathname)
import os
import glob
import pandas as pd
output_path = r'C:\\Users\\windows\\Documents\\test\\'
txt_files = glob.glob(os.path.join(output_path, 'Region_*.txt'))
for txt_file in txt_files:
df1 = pd.read_csv(txt_file, sep='\t')
print(df1)
Secondly, there is no need to initialize df1
with pd.DataFrame()
since pd.read_csv
already returns the built dataframe.
Solution 2:
the file path need to join the directory
for txt_file in txt_files:
print(txt_file) # here output is received as Region_CAN.txt
df1 = pd.DataFrame()
file_name = os.path.join(output_path, txt_file)
df1 = pd.read_csv(file_name,sep='\t')
print(df1)