pythonpandasdataframe

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'

Solution

  • 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.