简体   繁体   English

从 Python 中的文件夹读取文件

[英]Reading file from a folder in Python

I want to read Test.xlsx but the file is in another folder named 1 .我想阅读Test.xlsx但该文件位于另一个名为1的文件夹中。 Is there a way to specify the file location file_loc ?有没有办法指定文件位置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

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'尝试将路径字符串更改为原始字符串r'C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept12_2022\1\Test.xlsx'

because \1 converts to an emoji( ).因为\1转换为表情符号( )。

Or replace single slash \ with double slash \\ "C:\\Users\\USER\\OneDrive - Technion\\Research_Technion\\Python_PNM\\Sept12_2022\\1\\Test.xlsx"或将单斜杠\替换为双斜杠\\ "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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM