0

I'm trying to figure out how to use File Paths. This is the example that I am given but, it makes zero sense, I tried to copy the exact path that didn't work. I'm using Pycharm.

What I tested

file_path = 'D:\PycharmProjects\Standard_Library\pi_digits.txt'
with open(file_path) as file_object:

Book Example Below

file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
with open(file_path) as file_object:
Pablo
  • 1
  • Does this answer your question? [How to get an absolute file path in Python](https://stackoverflow.com/questions/51520/how-to-get-an-absolute-file-path-in-python) – Jochen Haßfurter Aug 17 '20 at 11:43
  • @Pablo Welcome to StackOverflow! I will suggest to start with something simple like [1] Try to read 'D:\pi_digits.txt' (just place this file under D: volume). [2] Then, create a folder, say 'Test1' and cut/copy-paste the file there, then you can read it using 'D:\Test1\pi_digits.txt'. – IamAshKS Aug 17 '20 at 12:11

1 Answers1

1

The author uses the Unix system and you are using the windows system and the only difference between the two examples is the file-separator.

In Python, you can declare separators either with hard-coded (For Unix: /, for windows: \)

But you can use os.path to remove the confusion of the os separator. Just place the text file in your current directory and you can use it in the example like below:

import os.path

text_file = 'pi_digits.txt'

file_path = os.path.join(os.getcwd(), text_file)
print(file_path)

Out:

/Users/PycharmProjects/StackOverFlow-pip/pi_digits.txt

Since I'm also using a Unix system my example is similar to the book example. But If you try it in your pc you will see similar to the below:

'D:\PycharmProjects\Standard_Library\pi_digits.txt'

Then you can open the text file and read it using with open(file_path) as file_object:

Ahmet
  • 7,527
  • 3
  • 23
  • 47