Home > Net >  Reading file from a folder in Python
Reading file from a folder in Python

Time:09-12

I want to read Test.xlsx but the file is in another folder named 1. Is there a way to specify the file location file_loc? I tried this but there seems to be an error.

import pandas as pd
import numpy as np


file_loc = "C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept12_2022\1\Test.xlsx"

df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols="A,C:AA")
A=df["N"].to_numpy()
print([A])

The error is

line 11
    file_loc = "C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept12_2022\1\Test.xlsx"
                                                                                                       ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

CodePudding user response:

Try to change your path string to a raw string r'C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept12_2022\1\Test.xlsx'

because \1 converts to an emoji().

Or replace single slash\ with double slash\\ "C:\\Users\\USER\\OneDrive - Technion\\Research_Technion\\Python_PNM\\Sept12_2022\\1\\Test.xlsx"

import pandas as pd
import numpy as np


file_loc = r"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept12_2022\1\Test.xlsx"

df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols="A,C:AA")
A=df["N"].to_numpy()
print([A])

  • Related