简体   繁体   中英

How do I read in a CSV file from my desktop in Python?

I am trying to read in a CSV file from my desktop:

My code is as follows:

import pandas as pd
import csv
from pathlib import Path

csv = r'C:\Users\nulli\OneDrive\Desktop\Work_Sample.csv'
df = pd.read_csv(csv, sep=',')

Error:

---> df = pd.read_csv(csv, sep=',')

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\nulli\\OneDrive\\Desktop\\Work_Sample.csv'

You shouldn't use backslashes for paths as Python has some special escape characters like \n that means newline or \t that means a tab. The easiest way is to always use standard slashes. You can also use:

r"some_path\with\backslashes"

to ignore escape characters and treat all backslashes as backslashes.

But the best way is to use a package which was designed to handle paths. pathlib is a great tool for that:

from pathlib import Path
my_csv = Path("C:/Usersnulli/OneDrive/Desktop/Work_Sample.csv")
df = pd.read_csv(my_csv.resolve(), sep=',')

resolve() returns a str from Path object.

And I think that it is often better to use relative paths - they will work for everyone without the need to update them. You can for example create a data folder in your workspace with the script and put the file there.

Also, you can check this out for more details regarding paths in Python.

use the following:

from pathlib import Path

csv = str(Path('C:\\Users\\nulli\\OneDrive\\Desktop\\Work_Sample.csv'))

After adding the slash after 'C:' , I would recommend trying / 's instead of \ 's in your path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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