This question already has answers here:
How to open a file for both reading and writing?
(4 answers)
Closed 6 years ago.
I'm trying to search through a file for a line that contain certain text and then replace that entire line with a new line.
I'm trying to use:
pattern = "Hello"
file = open('C:/rtemp/output.txt','w')
for line in file:
if pattern in line:
line = "Hi\n"
file.write(line)
I get an error saying:
io.UnsupportedOperation: not readable
I'm not sure what I'm doing wrong, please can someone assist.
You opened the file with 'w', meaning you are going to write to it. Then you try to read from it. So error.
Try reading from that file, and open another file for writing your output. If needed, when done, delete the first file and rename your output (temp) file to the first file's name.
You must be very new for python ^_^
You can write it like this:
pattern = "Hello"
file = open(r'C:\rtemp\output.txt','r') # open file handle for read
# use r'', you don't need to replace '\' with '/'
# open file handle for write, should give a different file name from previous one
result = open(r'C:\rtemp\output2.txt', 'w')
for line in file:
line = line.strip('\r\n') # it's always a good behave to strip what you read from files
if pattern in line:
line = "Hi" # if match, replace line
result.write(line + '\n') # write every line
file.close() # don't forget to close file handle
result.close()
Related
This question already has answers here:
write() versus writelines() and concatenated strings
(5 answers)
Closed 3 years ago.
I am trying to save some variables to a file on separate lines.
My code looks like this:
def saveall(sname, senemyname, scheckpoint,):
file = open("savefile.sav", "w")
file.writelines([sname, senemyname, scheckpoint])
file.close()
If I put saveall("John","Steve","Crossroads") in my code, I want it to make a file called savefile.sav, containing:
John
Steve
Crossroads
However, when I run the program, savefile.sav contains:
JohnSteveCrossroads
What am I doing wrong?
writelines expects each string to be newline terminated. So you need:
file.writelines([sname + '\n', senemyname + '\n', scheckpoint + '\n'])
From the python docs:
writelines(lines)
Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.
But usually it's more idiomatic to do file.write('\n'.join([sname, senemyname, scheckpoint)). Note that that doesn't add the file newline.
You should also be using contexts for files, because if an exception is raised you may not close your file:
with open('savefile.sav', 'w') as f:
f.write('\n'.join([sname, senemyname, scheckpoint]))
writelines doesn't add separators between the lines, so you have to add them yourself:
def saveall(sname, senemyname, scheckpoint,):
file = open("savefile.sav", "w")
file.writelines((line + '\n' for line in [sname, senemyname, scheckpoint]))
file.close()
saveall("John","Steve","Crossroads")
File content:
John
Steve
Crossroads
I have a problem whereby I am trying to first check a text file for the existence of a known string, and based on this, loop over the file and insert a different line.
For some reason, after calling file.read() to check for the test string, the for loop appears not to work. I have tried calling file.seek(0) to get back to the start of the file, but this has not helped.
My current code is as follows:
try:
f_old = open(text_file)
f_new = open(text_file + '.new','w')
except:
print 'Unable to open text file!'
logger.info('Unable to open text file, exiting')
sys.exit()
wroteOut = False
# first check if file contains an test string
if '<dir>' in f_old.read():
#f_old.seek(0) # <-- do we need to do this??
for line in f_old: # loop thru file
print line
if '<test string>' in line:
line = ' <found the test string!>'
if '<test string2>' in line:
line = ' <found test string2!>'
f_new.write(line) # write out the line
wroteOut = True # set flag so we know it worked
f_new.close()
f_old.close()
You already know the answer:
#f_old.seek(0) # <-- do we need to do this??
Yes, you need to seek back to the start of the file before you can read the contents again.
All file operations work with the current file position. Using file.read() reads all of the file, leaving the current position set to the end of the file. If you wanted to re-read data from the start of the file, a file.seek(0) call is required. The alternatives are to:
Not read the file again, you just read all of the data, so use that information instead. File operations are slow, using the same data from memory is much, much faster:
contents = f_old.read()
if '<dir>' in contents:
for line in contents.splitlines():
# ....
Re-open the file. Opening a file in read mode puts the current file position back at the start.
I am trying to add a line to the end of a txt file. I have been reading some posts here and trying differents options, but, for some reason, the new line is neved added after the last one, it is just appended next to the last one.
So I was wondering what I am doing wrong....here I am showing my tests:
TEST 1:
#newProt is a new data entered by the user in this case 12345
exists = False
f = open('protocols.txt', 'a+')
for line in f:
if newProt == line:
exists = True
if not exists:
f.write(newProt)
f.close()
txt file after this code:
2sde45
21145
we34z12345
TEST 2:
exists = False
with open('protocols.txt', 'r+') as f:
for line in f:
if newProt == line:
exists = True
if not exists:
f.write(newProt)
txt file after this code: exactly the same as above...
And, like this, I have tested some combinations of letters to open the file, rb+, w, etc but for some reason I never get the desired output txt file:
2sde45
21145
we34z
12345
So I do not know what I am doing wrong, I am following some examples I gor from some other posts here.
Try this:
exists = False
f = open('protocols.txt', 'a+')
for line in f:
if newProt == line:
exists = True
if not exists:
f.write('\n' + newProt)
f.close()
This adds the new line character to the end of the file then adds 'newProt'.
EDIT:
The reason why your code did not produce the desired result is because you were simply writing a string to the file. New lines in text are not really 'in' the text file. The text file is literally a series of bytes known as chars. The reason why various applications such as text editors show you new lines is because it interprets certain characters as formatting elements rather than letters or numbers.
'\n' is one such formatting character (in the ASCII standard), and it tells your favorite text editor to start a new line. There are others such as '\t' which makes a tab.
Have a look at the wiki article on Newline character for more info
You can use f.seek(-x,x), reach the last line and then f.write().
Otherwise my understanding is if you open a file in "a" (append) mode, it'll anyways be written in the end
Refer to this link: Appending line to a existing file having extra new line in Python
This question already has answers here:
How to jump to a particular line in a huge text file?
(17 answers)
Closed 8 years ago.
I want to read a text file line by line. I found how to read line by line by searching but not how to call a specific line in a text file. Basically, i want to do something with particular lines( like the first line, the second line, the third line, etc):
if particular_line is something:
....
Also, how can i do something like this:
if return_from_another_function in file:
....
Basically, i want an example of how i could do that if it's possible.
f = open('filename', 'r')
lines = f.readlines()
now you get a list type object lines which you can use to access particular line or iterate and search for particular line.
Probably this will help:
myfile = open(filename, "rb", 0)
for line in myfile
if(line is "your string to be compared")
print "do something here"
The standard linecache module makes this a snap:
import linecache
theline = linecache.getline(thefilepath, desired_line_number)
For your second que (from Ans):
If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):
if 'blabla' in open('example.txt').read():
print "true"
This question already has answers here:
How to print a file to stdout?
(11 answers)
Closed 9 years ago.
I'm trying to get Python to print the contents of a file:
log = open("/path/to/my/file.txt", "r")
print str(log)
Gives me the output:
<open file '/path/to/my/file.txt', mode 'r' at 0x7fd37f969390>
Instead of printing the file. The file just has one short string of text in it, and when I do the opposite (writing the user_input from my Python script to that same file) it works properly.
edit: I see what Python thinks I'm asking it, I'm just wondering what the command to print something from inside a file is.
It is better to handle this with "with" to close the descriptor automatically for you. This will work with both 2.7 and python 3.
with open('/path/to/my/file.txt', 'r') as f:
print(f.read())
open gives you an iterator that doesn't automatically load the whole file at once. It iterates by line so you can write a loop like so:
for line in log:
print(line)
If all you want to do is print the contents of the file to screen, you can use print(log.read())
open() will actually open a file object for you to read. If your intention is to read the complete contents of the file into the log variable then you should use read()
log = open("/path/to/my/file.txt", "r").read()
print log
That will print out the contents of the file.
file_o=open("/path/to/my/file.txt") //creates an object file_o to access the file
content=file_o.read() //file is read using the created object
print(content) //print-out the contents of file
file_o.close()