简体   繁体   English

如何使用 pandas 从我的计算机读取 csv 文件

[英]How read a csv file from my computer using pandas

I'm trying to read a CSV file that I have on my computer in a Jupyter Notebook.我正在尝试在 Jupyter Notebook 中读取我计算机上的 CSV 文件。 I using Pandas pd.read_csv(file path) but I'm getting this error:我使用 Pandas pd.read_csv(file path) 但出现此错误:

File "C:\Users\pc\AppData\Local\Temp/ipykernel_15328/2333079912.py", line 1
flight_df=pd.read_csv('C:\Users\pc\Desktop\Work\flight.csv')
                                                           ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: 
truncated \UXXXXXXXX escape

Here is my code so far:到目前为止,这是我的代码:

#Calling Libraries
import numpy as np
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt

flight_df=pd.read_csv('C:\Users\pc\Desktop\Work\flight.csv')

try C:/Users/pc/Desktop/Work/flight.csv or escape C:\\Users\\pc\\Desktop\\Work\\flight.csv otherwise \ is interpreted as escape sequence.尝试C:/Users/pc/Desktop/Work/flight.csv或转义C:\\Users\\pc\\Desktop\\Work\\flight.csv否则\被解释为转义序列。

If you change the string to either contain double backslashes \\ as directory separators or put a r in front of it like如果您将字符串更改为包含双反斜杠\\作为目录分隔符或在其前面放置r

flight_df=pd.read_csv(r'C:\Users\pc\Desktop\Work\flight.csv')

the loading of the file should succeed.文件的加载应该会成功。


As an addition, the error regards the escaping of characters like \U in C:\Users .此外,该错误与C:\Users中的\U等字符 escaping 有关。

Its because your path as treated as normal string.这是因为您的路径被视为普通字符串。 You can do this to fix your issue:您可以这样做来解决您的问题:

flight_df = pd.read_csv(r'C:\Users\pc\Desktop\Work\flight.csv')

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

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