How do you open text files in python3? [duplicate] - python

This question already has answers here:
Why am I getting a FileNotFoundError? [duplicate]
(8 answers)
Closed 1 year ago.
file = open('python-ai-info.txt', 'r')
words = file.read()
file.close()
Is this correct? Please help me fix it. I want to open file named python-ai-info.txt. I am currently getting error:
Traceback (most recent call last):
File "C:\Users\sgcoder1337\AppData\Local\Programs\Python\Python38-32\rhyme ai.py", line 1, in <module>
file = open('python-ai-info.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'python-ai-info.txt'

Your code is correct, the error occurs because your directory is an invalid/nonexistent directory, try to use the complete directory like:
'C:/Users/Username/Desktop/Folder/filename.txt'
For opening file:
file = open(directory, flag)
Main flags (modes) are:
"r" for reading text, throws an exception if the file doesn't exist
"rb" for reading bytes, throws an exception if the file doesn't exist
"w" for writing text, doesn't throw an exception if the file doesn't exist, but creates it
"wb" for writing bytes, doesn't throw an exception if the file doesn't exist, but creates it
"a" for appending text, throws an exception if the file doesn't exist
"ab" for appending bytes, throws an exception if the file doesn't exist
"x" for creating files without opening, throws an exception if the file already exist
For reading files:
txt = file.read() # get the whole text
line = file.readline() # get a line
lines = file.readlines() # get a list of lines
For writing text:
file.write('txt')
For closing:
file.close()
For more detailed and complete info have a look here

Related

"Peek of a closed file" right after file is opened

I'm trying to load data from a pickled object into a list, but despite opening the file, I am receiving
Traceback (most recent call last):
File "/path/to/file.py", line 18, in <module>
data.append(pickle.load(file))
ValueError: peek of closed file
I assumed that I missed something in opening the file, but I looked and what I have seemed fine to me (this is my first foray into IO with pickle)
# load data to list
with open('tasks.txt', 'rb') as file:
data = []
while True:
try:
data.append(pickle.load(file))
except EOFError:
break
file.close()
Am I handling the opening wrong, or is it something else?
You closed the file after the first load; remove the file.close() entirely (the with statement already handles that), and it should work fine.

How to solve - IOERROR : Fatal Error: File 'path/to/file' could not be located or is not readable

I have been trying to open a file by passing it as an argument.
I have been providing the correct file path and the file is also readable.
I created another script in order to determine whether the file is readable or not. I got the contents of the text file which shows that the file is readable and the path is also correct.
here is the piece trying to read the file -
try:
with open(args.filepath, "r") as file:
data = file.read()
except IOError:
print("Fatal Error: File "+args.filepath+" could not be located or is not readable.")
exit()
The file should be readable in the first place.

unable to create a text file using python

I am trying to learn the file I/O in python, I am trying following code to generate a text file in D drive of my computer with the statements written in the code but the compilation fails saying that the file 'I want to create' is not available which is obvious. How to create the file then?
file = open(r'D:/pyflie/text.txt',"w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
file.close()
and the error shown is
C:\Users\ssgu>python D:/pyfile/fw.py
Traceback (most recent call last):
File "D:/pyfile/fw.py", line 1, in <module>
file = open(r'D:/pyflie/text.txt',"w")
FileNotFoundError: [Errno 2] No such file or directory:
'D:/pyflie/text.txt'
You will get such an error if one of the specified directories does not exist. In this case, D:/pyflie/ does not exist yet, so it must be created beforehand. Then, your code should create and open the file normally. You can check upfront:
import os
if not os.path.exists(r"D:\pyflie"):
os.makedirs(r"D:\pyflie")
file = open(r'D:\pyflie\text.txt',"w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
file.close()
Also, check for typos in the path name. Did you mean D:/pyfile/?

Python get data from named pipe

How do I read from a named pipe in Python 3.5.3?
The pipe's name and location is /tmp/shairport-sync-metadata and it can be viewed by anybody, but only modified by the shairport-sync user.
Other websites and questions say to use os.mkfifo("pipe-location") but I've been getting this error:
>>> import os
>>> os.mkfifo("/tmp/shairport-sync-metadata")
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
os.mkfifo("/tmp/shairport-sync-metadata")
FileExistsError: [Errno 17] File exists
Is there a way to get around this? Sorry for the nooby question.
os.mkfifo is used to create fifo. Use open to open/read fifo already exist:
with open('/tmp/shairport-sync-metadata') as f: # add `rb` for binary mode
# line-by-line read
for line in f:
print(line)
# f.read(1024) # to read 1024 characters

Python: Deleting specific strings from file

I am reposting after changing a few things with my earlier post. thanks to all who gave suggestions earlier. I still have problems with it.
I have a data file (un-structed messy file) from which I have to scrub specific list of strings (delete strings).
Here is what I am doing but with no result:
infile = r"messy_data_file.txt"
outfile = r"cleaned_file.txt"
delete_list = ["firstname1 lastname1","firstname2 lastname2"....,"firstnamen lastnamen"]
fin = open(infile,"")
fout = open(outfile,"w+")
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()
When I execute the file, I get the following error:
NameError: name 'word' is not defined
I'm unable to replicate your error; the error I get with your code is the empty mode string - either put "r" or delete it, read is the default.
Traceback (most recent call last):
File "test.py", line 6, in <module>
fin = open(infile, "")
ValueError: empty mode string
Otherwise, seems fine!

Categories