+ 7
Opening files in python
A bit of a stupid question, but what does the full file name look like when opening from a Mac? I have been trying this code: myfile = open("/Users/myname/Downloads/filename.docx") And as expected I got error: FileNotFoundError: [Errno 2] No such file or directory Because I did not use the full file path name I guess? But how do I find out the full path name??
15 Respuestas
+ 5
Code Crasher very good!
"Automate the boring stuff "
Is nice too but my version is a bit outdated.
+ 4
Yeah so that's my question Oma Falk.. any idea how I find out what the full path name is?
+ 3
For beginners, whenever you are working with files, I suggst to do the following:
Put the files into the same directory like your code. That way you can access it with open("./filename.xyz")
If you would like to specify specific paths and you aren't sure about the way a complete path should be written as a string (depends on the operating system), run this code:
https://code.sololearn.com/ci0M98JQlj2l
(Your code needs to saved to a file for this to work).
This will give you the complete path to your current working directory as your operating system would stylize it. Then, just adapt it to your needs.
Or, if you are lazy, copy the file with the above code into the same folder in which the file you want to open is located and run it.
+ 2
Maybe your guess is true. Not full path.
Which os by the way?
+ 2
https://docs.python.org/3/library/os.path.html
U can look in Browser or play with relative paths.
I would recommend to use os and os.path
+ 1
myfile = open("//Users//myname//Downloads//filename.docx")
+ 1
That did not work either..
+ 1
I have a windows and had the same problem with python 3.6. Try updating it to a newer version and enter the full file source. The with open() command ought to work.
+ 1
First of all use with statement. open function is context manager so using with statement is more secure. Second, use os.path.join to build your path.
The easiest way is to define it like below:
```
from os import path
from functools import reduce
path_parts = ['C:', 'Users', 'MyUser', 'test.txt'] # Windows example
final_path = reduce(path.join, path_parts)
with open(final_path, 'r') as file:
content = file.readlines()
```
+ 1
To work with files I make use of pathlib.Path. Path(yourfile).exists(). If the path is correct it will return True otherwise False. Also I prefer pathlib over os as you work with objects.
0
I tried in dcode in mobile even it is saying "no such file". Why doesn't it work on Android mobile?
0
Does mobile has cmd?
0
It doesn't work in Android. At least not in SoloLearn
0
Y it doesn't work in android
0
Python File Open
❮ Previous Next ❯
f = open("demofile.txt", "r") print(f.read())
Open a file in a different location:
Return the 5 first characters of the file:
Read one line of the file:
Read two lines of the file:
Loop through the file line by line:
Close the file when you are finished with it:
Regards,
Will