anonymus
anonymus

Reputation: 49

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'

Upvotes: 1

Views: 5397

Answers (3)

Ayesha Pathan
Ayesha Pathan

Reputation: 63

For me in Jupyter lab I shut down and restarted the kernel as you suggested and it’s worked.

Upvotes: 0

Ynjxsjmh
Ynjxsjmh

Reputation: 29982

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.

Upvotes: 1

cherful
cherful

Reputation: 189

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)

Upvotes: 1

Related Questions