I'm trying to learn how to parse .txt files in Python. This has led me to opening the interpreter (terminal > python) and playing around. However, I can't seem to be able to specify the right path. Where does Python first look?
This is my first step:
f = open("/Desktop/temp/myfile.txt","file1")
This blatantly doesn't work. Can anyone advise?
That doesn't work as you've got the wrong syntax for open
.
At the interpreter prompt try this:
>>> help(open)
Help on built-in function open in module __builtin__:
open(...)
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object.
So the second argument is the open mode. A quick check of the documentation and we try this instead:
f = open("/Desktop/temp/myfile.txt","r")
Edit: Oh and yes, your second argument is wrong. Didn't even notice that :)
Python looks where you tell it to for file opening. If you open up the interpreter in /home/malcmcmul then that will be the active directory.
If you specify a path, that's where it looks. Are you sure /Desktop/temp is a valid path? I don't know of many setups where /Desktop is a root folder like that.
Some examples:
If I have a file: /home/bartek/file1.txt
And I type python
to get my interpreter within the directory /home/bartek/
This will work and fetch file1.txt ok: f = open("file1.txt", "r")
This will not work: f = open("some_other_file.txt", "r")
as that file is in another directory of some sort.
This will work as long as I specify the correct path: f = open("/home/media/a_real_file.txt", "r")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With