0

Python 3.6, OS Windows 7

I am trying to read a .txt using pd.read_csv() using relative filepath. So, from pd.read_csv() API checked out that the filepath argument can be any valid string path.

So, in order to define the relative path I use pathlib module. I have defined the relative path as:

df_rel_path = pathlib.Path.cwd() / ("folder1") / ("folder2") / ("file.txt")
a = str(df_rel_path)

Finally, I just want to use it to feed pd.read_csv() as:

df = pd.read_csv(a, engine = "python", sep = "\s+")

However, I am just getting an error stating "No such file or directory: ..." showing double backslashes on the folder path.

I have tried to manually write the path on pd.read_csv() using a raw string, that is, using r"relative/path". However, I am still getting the same result, double backslashes. Is there something I am overlooking?

FJSJ
  • 219
  • 3
  • 14

2 Answers2

0

You can get what you want by using os module

df_rel_path = os.path.abspath(os.path.join(os.getcwd(), "folder1", "folder2"))

This way the os module will deal with the joining the path parts with the proper separator. You can omit os.path.abspath if you read a file that's within the same directory but I wrote it for the sake of completeness.

For more info, refer to this SO question: Find current directory and file's directory

Colonder
  • 1,556
  • 3
  • 20
  • 40
  • I have tried but still the same results. I do not understand it. I am using the same philosophy for subprocess.Popen() and it is working perfectly. – FJSJ Jan 31 '19 at 10:18
  • Can you post the stacktrace? Are you sure you're pointing to a proper location? Does the file truly exist? – Colonder Jan 31 '19 at 10:33
  • Hi @Colonder. You were right. There was something wrong with `file.txt`. The problem was that I assumed the textfile extension was `("file.txt")` when it was not. It was `("file.out")` Nonetheless, I do not understand how using .txt extension (when it should be .out) you end up having double backslash in your paths. Thank you for your help! – FJSJ Jan 31 '19 at 11:37
  • On Windows, you have to use a double backslash in order to escape the \ sign – Colonder Jan 31 '19 at 11:47
0

You need a filename to call pd.read_csv. In the example 'a' is a only the path and does not point to a specific file. You could do something like this:

df_rel_path = pathlib.Path.cwd() / ("folder1") / ("folder2")
a = str(df_rel_path)
df = pd.read_csv(a+'/' +'filename.txt')

With the filename your code works for me (on Windows 10):

df_rel_path = pathlib.Path.cwd() / ("folder1") / ("folder2")/ ("file.txt")
a = str(df_rel_path)
df = pd.read_csv(a)
  • you are completely right. It was a mistake from my side not to specified the .txt file. But yes, I am pointing pd.read_csv() to a .txt file. I will correct the question then. – FJSJ Jan 31 '19 at 10:13