Leonardo
Leonardo

Reputation: 11

Problem loading .csv file with full path with Pandas

folks.

I am trying to create an input where the user enters the path of a file and this input is loaded to the pd.read_csv. Example:

import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

file_name = input("insert file name (and path): ")

dados = pd.read_csv(nome_arquivo, encoding = "UTF-8", header = 0, decimal=",", sep='\t')

And I get the following error message:

raceback (most recent call last):
  File "/Users/lsales/PycharmProjects/Propmec/Ensaio_tracao.py", line 42, in <module>
    dados = pd.read_csv(nome_arquivo, encoding = "UTF-8", header = 0, decimal=",", sep='\t')
  File "/Users/lsales/PycharmProjects/Propmec/venv/lib/python3.7/site-packages/pandas/io/parsers.py", line 676, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/Users/lsales/PycharmProjects/Propmec/venv/lib/python3.7/site-packages/pandas/io/parsers.py", line 448, in _read
    parser = TextFileReader(fp_or_buf, **kwds)
  File "/Users/lsales/PycharmProjects/Propmec/venv/lib/python3.7/site-packages/pandas/io/parsers.py", line 880, in __init__
    self._make_engine(self.engine)
  File "/Users/lsales/PycharmProjects/Propmec/venv/lib/python3.7/site-packages/pandas/io/parsers.py", line 1114, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "/Users/lsales/PycharmProjects/Propmec/venv/lib/python3.7/site-packages/pandas/io/parsers.py", line 1874, in __init__
    src = open(src, "rb")
FileNotFoundError: [Errno 2] No such file or directory: '/:Users/:lsales/:Downloads/:DS01.txt'

I have tried all variations like \\, :, etc.

Can anybody give me a help in this matter?

Thanks!

Upvotes: 0

Views: 66

Answers (1)

Umar.H
Umar.H

Reputation: 23099

As Quang noted you're not parsing your Mac OS path correctly, but what if the file does not truly exists or you make an error in future? it's not good to let your whole program crash because of this hiccup.

It's good practice to handle your errors or write code that can anticpiate them, lets try a While loop and test if a file exists using pathlib.

from Pathlib import Path 

while True:
    path = input("insert file name (and path): ")

    if Path(path).is_file():
        break
    print(f'{path} is not a valid file_path, please try again.')
    print(f"A valid example of your systems file path is: {Path.cwd()}")

Test.

insert file name (and path): test.csv
test.csv is not a valid file_path, please try again.
A valid example of your systems file path is: C:\Users\datanovice

Upvotes: 1

Related Questions