Reading file from a folder in Python

Question:

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:UsersUSEROneDrive - TechnionResearch_TechnionPython_PNMSept12_20221Test.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:UsersUSEROneDrive - TechnionResearch_TechnionPython_PNMSept12_20221Test.xlsx"
                                                                                                       ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated UXXXXXXXX escape
Asked By: user19862793

||

Answers:

Try to change your path string to a raw string
r'C:UsersUSEROneDrive - TechnionResearch_TechnionPython_PNMSept12_20221Test.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:UsersUSEROneDrive - TechnionResearch_TechnionPython_PNMSept12_20221Test.xlsx"

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

Answered By: codester_09
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.