Federer
Federer

Reputation: 34715

What is wrong with this code to open a file?

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?

Upvotes: 4

Views: 21584

Answers (8)

tdMJN6B2JtUe
tdMJN6B2JtUe

Reputation: 428

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)

Upvotes: 0

Flasknoobie
Flasknoobie

Reputation: 59

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

Upvotes: 2

Shakujin
Shakujin

Reputation: 74

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

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 113905

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)

Upvotes: 1

Abgan
Abgan

Reputation: 3716

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.

Upvotes: 3

David Webb
David Webb

Reputation: 193696

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

Upvotes: 11

Brent Newey
Brent Newey

Reputation: 4509

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

Upvotes: 4

Bartek
Bartek

Reputation: 15599

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

Upvotes: 10

Related Questions