File Not Found Error Python [duplicate] - python

This question already has answers here:
Why am I getting a FileNotFoundError? [duplicate]
(8 answers)
Closed 9 months ago.
I'm trying to read a file on a specific path with with open method. Normally I do this with no problem, but right now there is a txt file on a specific path and Python raising FileNotFoundError. I formatted the pc today, I don't know the problem is about this or not.
I added Python to path. Version is 3.5. I tried these lines at the beginning of file;
#!/usr/bin/env
import os
#!/usr/bin/env python
import os
#!/usr/bin/env python3
import os
none of this worked. Still got the error. How can I fix this error? Searched questions about this problem but there are no answer for me.
UPDATE AFTER COMMENTS
Full traceback is:
`File "C:\Users\windows\Desktop\go.py", line 4, in <module>
with open ("file") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'file'`
I'm trying to open this file with these codes;
with open ("file") as f:
t = f.readlines()
print (t)
The file is on the Desktop.

Just a guess. When you say "txt" file, do you mean the file has a ".txt" extension. If so, your code should include the extension.
with open ("file.txt") as f:
t = f.readlines()
print (t)

You need:
file = 'C:\Users\****\Desktop\1.txt'
with open (file) as f: # " inverted commas not required here
t = f.readlines()
print (t)

Related

Python cannot see csv file

I went through couple answers on forum already but without any success.
I am using Linux mint, Python 3.6.0 and i am trying to open CSV in Python but then error occurs:
file = open("~/Desktop/xyz/city.csv", "rb")
FileNotFoundError: [Errno 2] No such file or directory: '~/Desktop/xyz/city.csv'
My code:
import csv
file = open("~/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)
I also tried to move the file to desktop as in some answers i found, instead of path i used "city.csv". Still doesn't work.
Completely new to Linux and just can't find why this isn't working.
Each reply appreciated!
You should'nt use '~' to specify the path of your directory but the full path instead. E.g. :
import csv
file = open("/home/user/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)
If you need to use the tilde, you should then use os.path.expanduser('~/Desktop/xyz/city.csv'). E. g. :
import csv
file = open(os.path.expanduser("~/Desktop/xyz/city.csv"), "rb")
reader =csv.reader(file)
The reason for that is that the "tilde expansion" is a user interface feature that is not recognized by the file system: http://www.gnu.org/software/bash/manual/bashref.html#Tilde-Expansion
Try using the full file path, something like this:
file = open("/home/[username]/Desktop/xyz/city.csv", "rb")
Usually ~ does not expand properly. I have found that when it is needed, put $HOME environment variable value into a python variable and then use join to attach it as a prefix to the file name relative position. This also allows you to move the file to a different location and create a function that will allow you to redefine the prefix.

Python: How to fix an [errno 2] when trying to open a text file? [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 6 months ago.
I'm trying to learn Python in my free time, and my textbook is not covering anything about my error, so I must've messed up badly somewhere. When I try to open and read a text file through notepad (on Windows) with my code, it produces the error. My code is:
def getText():
infile = open("C:/Users/****/AppData/Local/Programs/Python/Python35-32/lib/book.txt" , "r")
allText = infile.read()
return allText
If it's necessary, here is the rest of my code so far:
def inspectWord(theWord,wList,fList):
tempWord = theWord.rstrip("\"\'.,`;:-!")
tempWord = tempWord.lstrip("\"\'.,`;:-!")
tempWord = tempWord.lower()
if tempWord in wList:
tIndex = wList.index(tempWord)
fList[tIndex]+=1
else:
wList.append(tempWord)
fList.append(1)
def main():
myText = getText()
print(myText)
main()
I'd greatly appreciate any advice, etc.; I cannot find any help for this. Thanks to anyone who responds.
To open a unicode file, you can do the following
import codecs
def getText():
with codecs.open("C:/Users/****/AppData/Local/Programs/Python/Python35-32/lib/book.txt" , "r", encoding='utf8') as infile:
allText = infile.read()
return allText
See also: Character reading from file in Python
First of all, I recommend you to use relative path, not absolute path. It is simpler and will make your life easier especially now that you just started to learn Python. If you know how to deal with commandline, run a new commandline and move to the directory where your source code is located. Make a new text file there and now you can do something like
f = open("myfile.txt")
Your error indicates that there is something wrong with path you passed to builtin function open. Try this in an interactive mode,
>> import os
>> os.path.exists("C:/Users/****/AppData/Local/Programs/Python/Python35-32/lib/book.txt")
If this returns False, there is nothing wrong with your getText fuction. Just pass a correct path to open function.

Errno 2 Python- No such file/directory [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 6 months ago.
I am an infant in the coding world (week 6) and I need some help! My overall goal is to write a program that inputs the file unsorted_fruits.tex, reads it, sorts the list alphabetically, and then writes it out to a file called sorted_fruits.txt.
So far I have my basics (aside from sorting and writing it into the new file)
infile=open("unsorted_fruits.tex", "r")
outfile=open("sorted_fruits.txt","w")
fruit=infile.read(26)
outfile.write(fruit)
unsorted_fruits.sort()
print (fruit)
infile.close()
outfile.close()
However I keep getting the [Errno 2] No such file or directory: 'unsorted_fruits.tex'
The file is definitely saved to my computer. I thought it might be .tex (I wasn't familiar with this format) so I changed the file to .txt. and called the .txt to see if that worked, no luck, so I changed it back to .tex
Any help is appreciated, thanks!!
Your code tries to find the text file in current directory. (For example, it can be the directory where Python interpreter is installed). So you may want to specify the absolute path. if text files are in the same dir with python script, you may want to use something like:
file_name = os.path.join(os.path.dirname(__file__), 'unsorted_fruits.tex')
with open(file_name, 'r') as f:
data = f.read()
(Note: I'm using "with" syntax while working with file, so I do not need to close it manually)

In Python, how to open a file for writing, but do not create it if the file does not exist? [duplicate]

This question already has answers here:
Difference between modes a, a+, w, w+, and r+ in built-in open function?
(9 answers)
Closed 7 years ago.
The file is a device under /dev. I don't want to mess things up so if the file does not exist, I should not create it. How to handle this in Python?
I hope this problem be solved by open method. That is, it should throw an IOError like mode "r" when the file does not exist. Don't redirect the question to "check if a file exists".
There's two ways to do this.
Either
from os.path import exists
if exists(my_file_path):
my_file = open(my_file_path, 'w+')
if you need to trigger things based on the file existing, that's the best way.
Otherwise, just do open(file_path, 'r+')
import os
if os.path.exists(dev):
fd = os.open(dev, os.O_WRONLY) # or open(dev, 'wb+')
...
Also check How to perform low level I/O on Linux device file in Python?
Here is a simple python script that shows the files in a directory, where their file is and whether the real file exists or not
import os
def get_file_existency(filename, directory):
path = os.path.join(directory, filename)
realpath = os.path.realpath(path)
exists = os.path.exists(path)
if exists:
file = open(realpath, 'w')
else:
file = open(realpath, 'r')

importing txt files into python

a01:01-24-2011:s1
a03:01-24-2011:s2
a02:01-24-2011:s2
a03:02-02-2011:s2
a03:03-02-2011:s1
a02:04-19-2011:s2
a01:05-14-2011:s2
a02:06-11-2011:s2
a03:07-12-2011:s1
a01:08-19-2011:s1
a03:09-19-2011:s1
a03:10-19-2011:s2
a03:11-19-2011:s1
a03:12-19-2011:s2
this is saved in animallog1.txt. How would I import this file so that it can be used to write code, or answer questions using the above data.
I have tried:
open('C:/animallog1.txt', 'r')
but it does not work and states
FileNotFoundError: [Errno 2] No such file or directory: 'C:/animallog1.txt'
Could someone please help me fix this
open('C:\\animallog1.txt', 'r')
Does file animallog1.txt exists?
On Windows you should be care for the backsplash.
file = open('c:\\path\\to\\file', 'r')
or
file = open(r'c:\path\to\file', 'r')
Check your workspace, u can use os.chdir() to change your directory to c:\?
First, if you're using Windows, you have to use backslashes. There are a couple ways to do that: one is with double backslashes as others have pointed out, another is using the various constants and functions in the os and os.path libraries:
import os
filename = "C:" + os.sep + "animallog1.txt"
Second, the "proper" way to do this is with a with statement:
with open(filename) as f: #'r' is default
for line in f:
a, date, s = line.split(":")
# ...
What the with statement does is guarantee that the file gets closed on leaving the with block. Otherwise the file doesn't get closed until the Python garbage collector gets around to it.

Categories

Resources