How to re sub a pattern in a file [duplicate] - python

I have this code:
line1 = []
line1.append("xyz ")
line1.append("abc")
line1.append("mno")
file = open("File.txt","w")
for i in range(3):
file.write(line1[i])
file.write("\n")
for line in file:
print(line)
file.close()
But when I try it, I get an error message like:
File "...", line 18, in <module>
for line in file:
UnsupportedOperation: not readable
Why? How do I fix it?

You are opening the file as "w", which stands for writable.
Using "w" you won't be able to read the file. Use the following instead:
file = open("File.txt", "r")
Additionally, here are the other options:
"r" Opens a file for reading only.
"r+" Opens a file for both reading and writing.
"rb" Opens a file for reading only in binary format.
"rb+" Opens a file for both reading and writing in binary format.
"w" Opens a file for writing only.
"a" Open for writing. The file is created if it does not exist.
"a+" Open for reading and writing. The file is created if it does not exist.

Use a+ to open a file for reading, writing and create it if it doesn't exist.
a+ Opens a file for both appending and reading. The file pointer is at
the end of the file if the file exists. The file opens in the append
mode. If the file does not exist, it creates a new file for reading
and writing. -Python file modes
with open('"File.txt', 'a+') as file:
print(file.readlines())
file.write("test")
Note: opening file in a with block makes sure that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.

There are few modes to open file (read, write etc..)
If you want to read from file you should type file = open("File.txt","r"), if write than file = open("File.txt","w"). You need to give the right permission regarding your usage.
more modes:
r. Opens a file for reading only.
rb. Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in binary format.
w. Opens a file for writing only.
you can find more modes in here

This will let you read, write and create the file if it don't exist:
f = open('filename.txt','a+')
f = open('filename.txt','r+')
Often used commands:
f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file

Sreetam Das's table is nice but needs a bit of an update according to w3schools and my own testing. Unsure if this due to the move to python 3.
"a" - Append - will append to the end of the file and will create a file if the specified file does not exist.
"w" - Write - will overwrite any existing content and will create a file if the specified file does not exist.
"x" - Create - will create a file, returns an error if the file exist.
I would have replied directly but I do not have the rep.
https://www.w3schools.com/python/python_file_write.asp

Related

Does python have a file opening mode which combines the features of "w+" and "r"?

I have a script which I use for requesting data from an external API. My script contains complex logic and describing it will take much time. At a certain point of my script I need to open a file, loop over it and and extract each value from it.
with open(os.path.abspath("/data/data/com.termux/files/home/storage/forecast/endpoints/leagueIdExtracted.txt"), "r+") as leagueIdExtracted:
print("Check is file {} was opened".format(leagueIdExtracted))
for id in leagueIdExtracted:
print("ID {} from opened file".format(id))
savedLeagues.add(int(str(id[:-1])))
print("League IDs {} from file which contain alredy requested IDs".format(savedLeagues))
But sometimes isn't up to me file which i open in above isn't exist
with open(os.path.abspath("/data/data/com.termux/files/home/storage/forecast/endpoints/leagueIdExtracted.txt"), "r+") as leagueIdExtracted:
Because of it while I open this file I have to open it in "w+" mode. Opening it in "w+" guarantees that a non-existing file will be created and opened. But while my script opened the file in "w+" mode it can't extract values from it.
for id in leagueIdExtracted:
print("ID {} from opened file".format(id))
savedLeagues.add(int(str(id[:-1])))
Because of it I have to manually switch between "w+" and "r" modes. Can anyone advise me whether Python has a mode which will create file while opening it if it does not exist as "w+" mode and also allow to extract data as
"r" mode?
You can use a+ as a mode. Using a+ opens a file for both appending and reading. If the file doesn't exist, it will be created.
# In this example, sample.txt does NOT exist yet
with open("sample.txt", "a+") as f:
print("Data in the file: ", f.read())
f.write("wrote a line")
print("Closed the file")
with open("sample.txt", "a+") as f:
f.seek(0)
print("New data in the file:", f.read())
Output:
Data in the file:
Closed the file
New data in the file: wrote a line
You should keep in mind that opening in a+ mode will place the cursor at the end of the file. So if you want to read data from the beginning, you will have to use f.seek(0) to place the cursor at the start of the file.
You want to use 'r+' if your objective is to read/write to existing files. In case you want to create new file as well, use 'a+'. In other words you will be able to do all of the follwing three.
1. Create if file does not exist
2. Write (append) if file exists
3. Read in file
Quoting from Reading and Writing Files: Python Documentation:
'r' when the file will only be read,
'w' for only writing (an existing file with the same name will be erased),
'a' opens the file for appending; any data written to the file is automatically added to the end.
'r+' opens the file for both reading and writing.

Python error message io.UnsupportedOperation: not readable

I have this code:
line1 = []
line1.append("xyz ")
line1.append("abc")
line1.append("mno")
file = open("File.txt","w")
for i in range(3):
file.write(line1[i])
file.write("\n")
for line in file:
print(line)
file.close()
But when I try it, I get an error message like:
File "...", line 18, in <module>
for line in file:
UnsupportedOperation: not readable
Why? How do I fix it?
You are opening the file as "w", which stands for writable.
Using "w" you won't be able to read the file. Use the following instead:
file = open("File.txt", "r")
Additionally, here are the other options:
"r" Opens a file for reading only.
"r+" Opens a file for both reading and writing.
"rb" Opens a file for reading only in binary format.
"rb+" Opens a file for both reading and writing in binary format.
"w" Opens a file for writing only.
"a" Open for writing. The file is created if it does not exist.
"a+" Open for reading and writing. The file is created if it does not exist.
Use a+ to open a file for reading, writing and create it if it doesn't exist.
a+ Opens a file for both appending and reading. The file pointer is at
the end of the file if the file exists. The file opens in the append
mode. If the file does not exist, it creates a new file for reading
and writing. -Python file modes
with open('"File.txt', 'a+') as file:
print(file.readlines())
file.write("test")
Note: opening file in a with block makes sure that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.
There are few modes to open file (read, write etc..)
If you want to read from file you should type file = open("File.txt","r"), if write than file = open("File.txt","w"). You need to give the right permission regarding your usage.
more modes:
r. Opens a file for reading only.
rb. Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in binary format.
w. Opens a file for writing only.
you can find more modes in here
This will let you read, write and create the file if it don't exist:
f = open('filename.txt','a+')
f = open('filename.txt','r+')
Often used commands:
f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file
Sreetam Das's table is nice but needs a bit of an update according to w3schools and my own testing. Unsure if this due to the move to python 3.
"a" - Append - will append to the end of the file and will create a file if the specified file does not exist.
"w" - Write - will overwrite any existing content and will create a file if the specified file does not exist.
"x" - Create - will create a file, returns an error if the file exist.
I would have replied directly but I do not have the rep.
https://www.w3schools.com/python/python_file_write.asp

How do you open specific text files on python?

I want to open specific lines from an ordinary text file in python. is there anyway to do this? and how?
presuming that you want the line m and the name file is file.txt
with open('file.txt') as f:
line = f.read().splitlines()[m]
print(line)
line is the line that you want.
If the lines are selected by line numbers which follow a consistent pattern, use
itertools.islice.
E.g. To select every second line from line 3 up to but not including line 10:
import itertools
with open('my_file.txt') as f:
for line in itertools.islice(f, 3, 10, 2):
print(line)
First lets see how to open a file to write:
f = open(‘filename.txt’, ‘w’)
Now we have opened a file named filename, in write mode. Write mode is indicated using ‘w’. If a file of that particular name is not present then a new file would be created.
It has created an object of that particular file and we can do all our operations on that particular object. Now we have created an object for writing. The command to write is:
text = “Hello Python”
f.write(text) ## or f.write(“Hello Python”)
After doing all our required operations, we need to close the file. The command to close the file is as follows:
f.close()
This will save the file and close it. Now lets see how to read a file.
f = open(‘filename.txt’, ‘r’)
Same like write, but only the mode is changed to ‘r’. Now we have opened a file named filename, in read mode. Read mode is indicated using ‘r’. If a file of that particular name is not present then an error will be raised
Traceback (most recent call last):
File "", line 1, in
IOError: [Errno 2] No such file or directory: 'filename.txt'
If the file is present, then it would create an object of that particular file and we can do all our operations on that particular object. Now we have created an object for reading. The command to read is:
text = f.read()
print text
All the contents of the file object is now read and stored in the variable text. Text holds the entire contents of the file.
After doing all our required operations, we need to close the file. The command to close the file is as follows:
f.close()
In the above examples we have opened the file separately and close it separately, there is a better way to do it using with function. The modified code will be
with open(‘filename.txt’, ‘r’) as f:
text = f.read()
print text
When it comes out of the with block it will automatically close the file.

Python File I/O:How to know if text exist on a line and go to the next line

In python file io I get just frustrated because, when I try to write to the next line it just doesnt seem to work.
Ive tried "\n" but It just erases the existing text in the file
fo = open("acckeys.txt","w+")
fo.write(psw+"_"+usr+"\n")
So how would I check if text already exists in a line and write to the next line without erasing the existing text?
If you open the file with the append flag, it will write to the next free line.
fo = open("file.txt", "a")
Note you can also open with "a+" to allow reading as well.
"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.
With respect to the statement
fo = open("acckeys.txt")
It will open the acckeys.txt file in a read mode, I assume this file already exists, Otherwise It will throw IOError with the error message "No such file or directory: 'acckeys.txt'"
And This line will write to the file from the pointer it is currently pointing to. You can find out the current pointer using seek() of file handle, (fo in this case). Usually current offset pointer is the starting of file.
fo.write(psw+"_"+usr+"\n")
Now your question
So how would I check if text already exists in a line and write to the next line without erasing the existing text?
In order to check if the text exist in the file, you can read the file using
fileContent = fo.read()
And then check for the length of fileContent.
If you open a file in an append mode like this
fo = open("acckeys.txt" ,"a")
then irrespective of the file content or non-existent of the file itself. It will create a file incase of non-existent or set the offset pointer to the last line.

Why can't I write to a file that I open in python?

I opened the python interpreter and tried to write to a file I was reading at the same time:
file = open("foo.txt")
lines = file.readlines()
for i in range(0, 3):
file.write(lines[0])
However, python issued an error that noted I had a bad file handler when I tried to execute file.write(lines[0]). Why can't I write the first line of a file to the file itself?
In order to write to a file, it's necessary to open the file in write or read/write mode
file = open("foo.txt", "r+")  # reading and writing to file
or
file = open("foo.txt", "w") # writing only to file
If you open a file and don't specify a mode, it's in read mode by default, so you had opened your file for "read", but were trying to "write" to it.
See Reading and Writing Files Python Docs for more information. #Mizuho also suggested this page about Python File IO which has a very nice summary of the various modes available.

Categories