Editing specific line in text file in Python
You want to do something like this:
# with is like your try .. finally block in this case
with open('stats.txt', 'r') as file:
# read a list of lines into data
data = file.readlines()
print data
print "Your name: " + data[0]
# now change the 2nd line, note that you have to add a newline
data[1] = 'Mage\n'
# and write everything back
with open('stats.txt', 'w') as file:
file.writelines( data )
The reason for this is that you can't do something like "change line 2" directly in a file. You can only overwrite (not delete) parts of a file - that means that the new content just covers the old content. So, if you wrote 'Mage' over line 2, the resulting line would be 'Mageior'.
How to edit a text file at a specific line or location
I'd use regular expressions to match and replace text inside your file
import re
def search_write_in_file(file_name, string_to_search, description):
with open(file_name, 'r+') as file_obj:
text = file_obj.read()
new_text = re.sub(string_to_search,r"\1 {0}\n".format(description),text)
with open(file_name, 'w') as file_obj:
file_obj.write(new_text)
print(new_text)
if __name__ == '__main__':
search_write_in_file('text_to_edit.txt',r'(DATATYPE2;\n)',"test2")
search_write_in_file('text_to_edit.txt',r'(DATATYPE4;\n)',"test4")
This will update the existing file to be
VAR_GROUP
Var1 : DATATYPE1;(Description Var)
Var2 : DATATYPE2; test2
Var3 : DATATYPE3;(Description Var3)
Var4 : DATATYPE4; test4
END_GROUP
python how to write to specific line in existing txt file
You can read the file and then, write into some specific line.
line_to_replace = 17 #the line we want to remplace
my_file = 'myfile.txt'
with open(my_file, 'r') as file:
lines = file.readlines()
#now we have an array of lines. If we want to edit the line 17...
if len(lines) > int(line_to_replace):
lines[line_to_replace] = 'The text you want here'
with open(my_file, 'w') as file:
file.writelines( lines )
Selecting a specific index, in a specific line in an external text file to alter
My solution is the least complicated among others, I think.
- You should first read the lines of the characters.txt to a list like this:
lines = open("char.txt", "r").readlines()
- Next you need to change the text you want (yes to no), which is in 2nd line:
lines[1] = lines[1].replace("yes", "no")
- Lastly, you need to write everything back to file:
open("char.txt", "w").writelines(lines)
Final Code:
lines = open("char.txt", "r").readlines()
lines[1] = lines[1].replace("yes", "no")
open("char.txt", "w").writelines(lines)
If other fellows have anything to add, please comment on this. Thanks.
Edit specific line at specific position in Text file in Python
Simply open the existing file and read the lines. Assuming that you want to replace the values that always follow 'addmoney' and 'netmoney', you can locate those lines and use re.sub()
to substitute the values into those lines. Keep in mind that you can't simply overwrite text files in-place, so you store the modified lines and then recreate a new file at the end, like so:
x1 = 123.12
y1 = 123.45
import re
with open('mytextfile.txt', 'r') as f:
lines = f.readlines()
for i, l in enumerate(lines):
if l.startswith('addmoney'):
lines[i] = re.sub(r'[0-9.]+', str(x1), lines[i])
elif l.startswith('netmoney'):
lines[i] = re.sub(r'[0-9.]+', str(y1), lines[i])
out = open('modifiedtextfile.txt', 'w'); out.writelines(lines); out.close()
Python Replace content in specific line at txt file
Instead of that, what you can do is go with this code for editing the text file
with open(path_to_text_file,'r') as txt:
text=txt.readlines()
text[3]='phone number\n'
with open(path_to_text_file,'w') as txt:
txt.writelines(text)
How to write to a specific line in file in Python?
with open('input') as fin, open('output','w') as fout:
for line in fin:
fout.write(line)
if line == 'xxxxx\n':
next_line = next(fin)
if next_line == 'yyyyy\n':
fout.write('my_line\n')
fout.write(next_line)
This will insert your line between every occurrence of xxxxx\n
and yyyyy\n
in the file.
An alternate approach would be to write a function to yield lines until it sees an xxxxx\nyyyyy\n
def getlines(fobj,line1,line2):
for line in iter(fobj.readline,''): #This is necessary to get `fobj.tell` to work
yield line
if line == line1:
pos = fobj.tell()
next_line = next(fobj):
fobj.seek(pos)
if next_line == line2:
return
Then you can use this passed directly to writelines
:
with open('input') as fin, open('output','w') as fout:
fout.writelines(getlines(fin,'xxxxx\n','yyyyy\n'))
fout.write('my_line\n')
fout.writelines(fin)
Related Topics
Python: Pandas Merge Multiple Dataframes
Using Pip Behind a Proxy with Cntlm
Checking Multiple Values for a Variable
Getting "Permission Denied" When Running Pip as Root on My MAC
How to Check If a String Contains an Element from a List in Python
Why Python 3.6.1 Throws Attributeerror: Module 'Enum' Has No Attribute 'Intflag'
Unicodedecodeerror: 'Utf8' Codec Can't Decode Byte 0Xa5 in Position 0: Invalid Start Byte
Why Does the Print Function Return None
Why Don't These List Operations Return the Resulting List
Python Strings and Integer Concatenation
Sqlite Parameter Substitution Problem
Determine Function Name from Within That Function (Without Using Traceback)
Difference Between Class and Instance Methods