Reputation: 563
I want to read a text file using python. I've done it already in my old laptop and desktop computer, but when I try it on new system, error appears: file directory is not valid and file doesn't exist.
txtFile = open("D:/folder/m.txt")
I can't even install external libraries which contains the code above! I am using windows 8 and latest python 2.7
edit: guys, my main problem is the open() method always returns "file directory is not valid","There is no such a file in that directory" even when it's completely valid and exist! I tied it with various files and directories and it doesn't work at all. it works on my old systems but not working on this new laptop. I can't even use external libraries because the open() method is not working in anywhere even in libraries. please help me.
Upvotes: 1
Views: 23173
Reputation: 1533
with open('file.txt', 'r+') as f:
builtins.py says:
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
Upvotes: 2
Reputation: 1520
An old question I know.
Can be defined in the system record "Open with ".
But the extension may be undefined, in such cases just use the file name and never write the extension.
For more information, investigate MIME-TYPES and Default-Aplication.
Upvotes: 0
Reputation: 15320
Try this:
txtFile = open('D:\\folder\\m.txt', 'r')
Edit#1: you can use os.getcwd()
to get the current working directory (import os
) and then you won't have to use the slashes at all.
Edit#2: If all else fails, I would refer you to here where I think you can find what you're looking for.
Edit#3: It's a directory?! You never said that. I now officially don't understand what is your goal here.
Upvotes: 0
Reputation: 25
If you type on Windows, you should always use \
instead of /
when input the path of a file.
Also, always notice the Escape Character. Use \\
if you are not sure.
Err...we can also add an r
before the path.
So, try this below.
txtFile = open("D:\\folder\\m.txt")
txtFile = open(r"D:\folder\m.txt")
Both of them should work.
Upvotes: 1
Reputation:
Is that the actual name because it look like a directory. If you want to open a file make sure to open it in a mode as well.Make sure to open the file with it's actual name, otherwise I dunno??
Upvotes: 0