4

I tried this code to open a file in Python:

f = open("/Desktop/temp/myfile.txt","file1")

It didn't work. I think this is because I didn't specify the right path. How can I fix the problem?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Federer
  • 33,677
  • 39
  • 93
  • 121
  • works for me, check your path – ennuikiller Nov 03 '09 at 16:50
  • 2
    @ennuikiller - really? What mode is it opened in? – Dominic Rodger Nov 03 '09 at 16:52
  • When I encountered this question just now, it had a completely inappropriate title - the problem actually has nothing to do with the file path, despite the original misunderstanding. This means it was potentially misleading (or failing to help) thousands of viewers. Since the question didn't include proper debugging information, it should have been closed back when it was asked. The error message would have directly explained the problem, and **reading** it makes it **abundantly** clear that the path isn't the problem. – Karl Knechtel Sep 03 '22 at 23:28
  • (Well, the path is likely a problem, but not the one reported. Stack Overflow questions are supposed to be about **one** problem at a time, and show a proper [mre] so that they can be answered clearly without entangling the other problems. I am probably going to write a new QA pair for the path problem, because we desperately need a good one.) – Karl Knechtel Sep 03 '22 at 23:30
  • Actually, never mind: we have https://stackoverflow.com/questions/12201928. – Karl Knechtel Sep 03 '22 at 23:36

8 Answers8

11

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")
David Webb
  • 190,537
  • 57
  • 313
  • 299
10

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")

Bartek
  • 15,269
  • 2
  • 58
  • 65
  • Thanks! I wasn't too sure where it would first look and I didn't fancy specifying every single director! Thanks again! – Federer Nov 03 '09 at 16:52
4

To begin with, the second argument is the permissions bit: "r" for read, "w" for write, "a" for append. "file1" shouldn't be there.

Brent Newey
  • 4,479
  • 3
  • 29
  • 33
3

Try:

f = open('Desktop/temp/myfile.txt', 'r')

This will open file relatively to current directory. You can use '/Desktop/temp/myfile.txt' if you want to open file using absolute path. Second parameter to open function is mode (don't know what file1 should mean in your example).

And regarding the question - Python follows OS scheme - looks in current directory, and if looking for modules, looks in sys.path afterwards. And if you want to open file from some subdirectory use os.path.join, like:

import os
f = open(os.path.join('Desktop', 'temp', 'myfile.txt'), 'r')

Then you're safe from the mess with '/' and '\'.

And see docs for built-in open function for more information about the way to use open function.

David Koelle
  • 20,726
  • 23
  • 93
  • 130
Abgan
  • 3,696
  • 22
  • 31
2

Just enter your file name and there is your data.....what it does?---->If path exists checks it is a file or not and then opens and read

import os
fn=input("enter a filename: ")
if os.path.exists(fn):
    if os.path.isfile(fn):
        with open(fn,"r") as x:
            data=x.read()
            print(data)
    else:
        print(fn,"is not a file: ")
else:
    print(fn,"file doesnt exist ")
Venkatachalam
  • 16,288
  • 9
  • 49
  • 77
1

This:

import os
os.path

should tell you where python looks first. Of course, if you specify absolute paths (as you have), then this should not matter.

Also, as everyone else has said, your second argument in open is wrong. To find the proper way of doing it, try this code:

help(open)
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
1

A minor potential issue that the original post does not have but, also make sure the file name argument uses '/' and not '\'. This tripped me up as the file inspector used the incorrect '/' in its location.

'C:\Users\20\Documents\Projects\Python\test.csv' = Does not work

'C:/Users/20/Documents/Projects/Python/test.csv' = Works just fine

Shakujin
  • 64
  • 8
0
from pathlib import Path
import os

desired_directory = Path('C:/')
desired_directory = desired_directory / 'subfolder'
os.chdir(desired_directory)

That will force Python to look at the directory in the path you specify. It works well when using `subprocess.Popen' to use binary files, as in this snippet:

from subprocess import Popen
from shutil import which
instance_of_Popen = Popen(which('name_of_executable'))
print(instance_of_Popen.args)
brethvoice
  • 350
  • 1
  • 4
  • 14
  • Obviously the above snippet assumes you are using windows (uses a drive letter). For POSIX, you would pass \usr\home or something like that instead as your `Path` base. – brethvoice Aug 28 '20 at 17:40
  • See this answer to a different question for more details and look in the comments for a possibly useful link if you are using `subprocess.Popen' – brethvoice Aug 28 '20 at 17:43