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)
Related
This question already has answers here:
What is the python "with" statement designed for?
(11 answers)
Closed 6 months ago.
Running below code in Azure Blobstorage concurrently is throwing
OS Error 22:Invalid argument pointing to f.close()
Is using Close() when using with open() creating OS error 22 issues?
Understand that Close() is not required but want to understand the root cause of OS error 22
*with open(openfilepath,"w+") as f:
f.write(writeFile )
f.close()*
Check the below possibilities and try.
1
If f.close() to be used you may try this by not using with
f = open(file_name, 'w+') # open file in write mode
f.write('write content')
f.close()
BUT
It is good practice to use with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes. once Python exits from the “with” block, the file is automatically closed.
So Please Remove f.close() and try.
with open(file_name, 'w+') as f :
f.write('write content')
Refer this for more info.
2
If above doen’t work check the filepath : It might be due to some invalid characters present in the file path name: It should not contain few special characters.
See if file path is for example : "dbfs:/mnt/data/output/file_name.xlsx"
Check if “/” is there before dbfs ( say /dbfs:/mnt/…).Try Removing if present.
NOTE:
``r+'': Open for reading and writing. The stream is positioned at
the beginning of the file.
``w+'': Open for reading and writing. The file is created if it does
not exist, otherwise it is truncated. The stream is positioned at the
beginning of the file.
``a+'' : Open for reading and writing. The file is created if it does
not exist. The stream is positioned at the end of the file. Subse-
quent writes to the file will always end up at the then current end of
file, irrespective of any intervening fseek(3) or similar.
So try using other modes like r+ if w+ is not mandatory .See Python documentation
References:
1 , 2 ,3 , 4
Removing the F.close() fixed the issues when using With
This question already has answers here:
How to open a file for both reading and writing?
(4 answers)
Closed 3 years ago.
In simplest terms, when i try to run a short amount of code to delete the contents of a file and then rewrite stuff to that file, it pulls that error. I'm trying to get a temperature reading from a com port using the filewrite from CoolTerm, perhaps it's the fact that the file is being used by CoolTerm as well, so I can't edit it, but I'm unsure.
I've tried multiple ways to delete the file information e.g the file.close(), and others, but none seem to work.
while True:
file = open("test.txt","r")
file.truncate()
x = file.read()
x = x.split("\n")
print(x[0])
print(x[1])
time.sleep(3)
I expect the console to output the contents of file but it doesn't. Something that gives me a similar result of what i want would be the Console just outputting the last two entries of the file, rather than having to delete all of it than rewriting it.
Modified to r+ mode is ok, I have tested.
with open('./install_cmd', 'r+') as f:
print(f'truncate ago:{f.read()}')
f.truncate(0)
print(f'truncate after:{f.read()}')
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.
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)
This question already has answers here:
Create empty file using python [duplicate]
(2 answers)
Closed 8 years ago.
This is the code I have so far, yes I know the 'dirs' code creates a folder, but I am not sure of the code (if there is one) to create a file instead!
import os
if os.path.isfile(outfile):
print("Name already used, please choose another")
else:
os.makedirs(outfile)
Any help would be appreciated :D
Inorder to create a file and work on it, use the open() function.
fp = open(outfile, mode)
modes:
r: read
w: if file exists, replace it with a new one
a: append existing file
In your case the mode is 'w'
For create a file you can just open a file in write mode
open('file.txt', 'w')
https://docs.python.org/3/library/functions.html#open