I have a text file like below
Mo, M, 15,
Jen, F, 14
My code below replaces the age for 'Mo'
newAge = "20"
result = ""
with open("file.txt") as f:
for line in f:
if line.lower().startswith( "mo," ):
list = line.split()
list[2] = str( newAge )
line = ", ".join( list )
result += line + '\n'
f = open("file.txt", 'w')
f.write(result)
f.close()
How ever the file afterwards look like
[,',,M,,o,,M,,2,,0,,',]
How to I format it to look like the:
Mo, M, 20,
Use the csv module for both reading and writing the file. Below is a tested example.
newAge = ' 20'
result = []
with open('file.txt','rb') as fin, open('file_out.txt','wb') as fou:
cr = csv.reader(fin)
cw = csv.writer(fou)
for line in cr:
if line[0].lower() == "mo":
line[2] = newAge
cw.writerow(line)
You could try this instead:
newAge = "20"
result = ""
with open("file.txt") as f:
for line in f:
if line.lower().startswith( "mo," ):
list = line.split()
list[2] = newAge
line = ''
for element in list:
line += str(element)
line += ', '
result += line + '\n'
with open('file.txt', 'w') as inf:
inf.write(result)
If you're particular about the space at the end of the last element, you could even do:
newAge = "20"
result = ""
with open("file.txt") as f:
for line in f:
if line.lower().startswith( "mo," ):
list = line.split()
list[2] = newAge
line = ''
for index, element in enumerate(list):
line += str(element)
if not index is len(list) -1:
line += ', '
else:
line += ','
result += line + '\n'
with open('file.txt', 'w') as inf:
inf.write(result)
like #azalea mentioned, use .split(', '). Also, you should only use the newline character on strings you build because the existing strings already contain the new line.
newAge = "20"
result = ""
with open("file.txt") as f:
for line in f:
if line.lower().startswith("mo"):
list = line.split(', ')
list[2] = str(newAge)
line = ", ".join(list) + '\n'
result += line
f = open("file2.txt", 'w')
f.write(result)
f.close()
You split the line by space...then you should join it by space!
newAge = "20"
result = ""
with open("file.txt") as f:
for line in f:
if line.lower().startswith( "mo," ):
list = line.split()
list[2] = str( newAge )
line = " ".join( list )+"\n"
result += line
f = open("file.txt", 'w')
f.write(result)
f.close()
I prefer using keeping it simple . Just use the string module.
You can use it in this way.
import string
toFind = '15'
newAge = '20'
with open('file.txt','r') as f:
text = f.readlines()
text[0] = string.replace(text[0],toFind,newAge)
with open('file.txt','w') as f:
for item in text:
f.write(item)
I hope this helps!
Related
Good, I currently have the following code:
n = 0
with open('/home/user/test.filter') as f:
lines = f.readlines()
for l in lines:
if lines[n].startswith('-A vlan_8'):
if "-o bond1.8" in lines[n]:
f = open('vlan8.filter_in', 'a')
f.write(l)
else:
f = open('vlan8.filter_out', 'a')
f.write(l)
if lines[n].startswith('-A vlan_10'):
if "-o bond1.10" in lines[n]:
f = open('vlan10.filter_in', 'a')
f.write(l)
else:
f = open('vlan10.filter_out', 'a')
f.write(l)
if lines[n].startswith('-A vlan_15'):
if "-o bond1.15" in lines[n]:
f = open('vlan15.filter_in', 'a')
f.write(l)
else:
f = open('vlan15.filter_out', 'a')
f.write(l)
# [...]
n = n + 1
I thought about optimizing it with some accumulator or list to not make the script so extensive. Any suggestions?
Sure you can. Maintain a list of these numbers as so:
numList = [8, 10, 15, ...]
Now, all you need is a little string formatting.
with open('/home/user/test.filter') as f:
lines = f.readlines()
for i, l in enumerate(lines): # I've used enumerate to eliminate n but really you don't need it
for num in numList:
if l.startswith('-A vlan_%d' %num):
if "-o bond1.%d" %num in l:
f = open('vlan%d.filter_in' %num, 'a')
else:
f = open('vlan%d.filter_out' %num, 'a')
f.write(l)
f.close()
break
I think you want to make the code cleaner, not faster. If that is so maybe this would work:
import re
parameter_re = re.compile(r'^-A vla_(\d+).*')
with open('data.csv') as f:
lines = f.readlines()
for line in lines:
# Match required parameter
match = parameter_re.match(line)
# Skip line if it doesn't match the required parameter
if not match:
continue
# Extract number from parameter
number = int(match.group(1))
# Create output parameter string
output_str = '-o bond1.%d' % number
# Select correct filename to save the line
if output_str in line:
output_filename = 'vlan%d.filter_in' % number
else:
output_filename = 'vlan%d.filter_out' % number
# Write the line to the correct file
with open(output_filename, 'a') as f:
f.write(line)
And if you want to make it shorter (which I don't recommend, better for it to be readable):
import re
with open('data.csv') as f:
lines = f.readlines()
for line in lines:
match = re.match(r'^-A vla_(\d+).*', line)
if not match:
continue
number = int(match.group(1))
if '-o bond1.%d' % number in line:
output_filename = 'vlan%d.filter_in' % number
else:
output_filename = 'vlan%d.filter_out' % number
with open(output_filename, 'a') as f:
f.write(line)
I have a text file which has the following contents such
ABC
AAD
ABE
Where A=5, B=1, C=31, D=101 and E=4.
Expected output should be
5,1,31
5,5,101
5,1,4
The problem is only the last line of the text file is being converted to number.
Here is what I have tried so far;
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
with open('input.txt') as f:
content = f.readlines()
for i,j in enumerate(content):
my_text = content[i]
new_text = ','.join([my_text[i] for i in range(1, len(my_text), 1)])
reps = {'A':'5','B':'1','C':'31','D':'101','E':'4'}
txt = replace_all(new_text, reps)
with open('results.txt', 'a') as my_new_file:
my_new_file.write(txt)
What am I doing wrong?
You can write the whole thing much more simply as
reps = {'A':'5','B':'1','C':'31','D':'101','E':'4'}
with open('input.txt') as f, open('results.txt', 'w') as new_file:
for line in f:
new_text = ",".join(reps.get(char, char) for char in line)
new_file.write(new_text)
Your code only takes into account the value of new_text in the last iteration, which is the last line.
You should move all the logic inside the for loop.
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
with open('input.txt') as f:
content = f.readlines()
reps = {'A':'5','B':'1','C':'31','D':'101','E':'4'}
with open('results.txt', 'a') as my_new_file:
for i,j in enumerate(content):
my_text = content[i]
new_text = ','.join([my_text[i] for i in range(1, len(my_text), 1)])
txt = replace_all(new_text, reps)
my_new_file.write(txt)
You can try this using list comprehension:
f = open('input.txt').readlines()
f = [i.strip('\n') for i in f]
reps = {'A':'5','B':'1','C':'31','D':'101','E':'4'}
new_list = [[reps[b] for b in i] for i in f]
new_file = open('results.txt', 'a')
for i in new_list:
new_file.write(','.join(i))
new_file.write('\n')
new_file.close()
Couldn't help myself:
# create a lookup table
lookup = {
'A': '5',
'B': '1',
'C': '31',
'D': '101',
'E': '4'
}
# open the input file and the output file
with open('input.txt', 'r') as f, open('results.txt', 'w') as f_new:
# for each line...
for line in f.readlines():
# ...construct a new line...
nums = [lookup[character] for character in line.strip()]
newline = ','.join(nums) + '\n'
# ... and save the new line to the result file
f_new.write(newline)
I'm trying to replace a value in a specific line in a text file.
My text file contains count of the searchterm, searchterm & date and time
Text file:
MemTotal,5,2016-07-30 12:02:33,781
model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075
How can I replace for example the count of the searchterm for line 2 (model name,3,2016-07-30 13:37:59,074)?
This is what I have already:
f = open('file.log','r')
filedata = f.read()
f.close()
newdata = filedata.replace("2", "3")
f = open('file.log', 'w')
f.write(newdata)
f.close()
It replace all values 2.
You have to change three things in your code to get the job done:
Read the file using readlines.
filedata = f.readlines()
Modify the line you want to change (keep in mind that Python indices start at 0 and don't forget to add a newline character \n at the end of the string):
filedata[1] = 'new count,new search term,new date and time\n'
Save the file using a for loop:
for line in filedata:
f.write(line)
Here is the full code (notice I used the with context manager to open/close the file):
with open('file.log', 'r') as f:
filedata = f.readlines()
filedata[1] = 'new count,new search term,new date and time\n'
with open('file.log', 'w') as f:
for line in filedata:
f.write(line)
My solution:
count = 0
line_number = 0
replace = ""
f = open('examen.log','r')
term = "MemTotal"
for line in f.read().split('\n'):
if term in line:
replace= line.replace("5", "25", 1)
line_number = count
count = count + 1
print line_number
f.close()
f = open('examen.log','r')
filedata = f.readlines()
f.close()
filedata[line_number]=replace+'\n'
print filedata[line_number]
print filedata
f = open('examen.log','w')
for line in filedata:
f.write(line)
f.close()
You only need to define the searchterm & the replace value
I want to replace string in a line which contain patternB, something like this:
from:
some lines
line contain patternA
some lines
line contain patternB
more lines
to:
some lines
line contain patternA
some lines
line contain patternB xx oo
more lines
I have code like this:
inputfile = open("d:\myfile.abc", "r")
outputfile = open("d:\myfile_renew.abc", "w")
obj = "yaya"
dummy = ""
item = []
for line in inputfile:
dummy += line
if line.find("patternA") != -1:
for line in inputfile:
dummy += line
if line.find("patternB") != -1:
item = line.split()
dummy += item[0] + " xx " + item[-1] + "\n"
break
outputfile.write(dummy)
It do not replace the line contain "patternB" as expected, but add an new line below it like :
some lines
line contain patternA
some lines
line contain patternB
line contain patternB xx oo
more lines
What can I do with my code?
Of course it is, since you append line to dummy in the beginning of the for loop and then the modified version again in the "if" statement. Also why check for Pattern A if you treat is as you treat everything else?
inputfile = open("d:\myfile.abc", "r")
outputfile = open("d:\myfile_renew.abc", "w")
obj = "yaya"
dummy = ""
item = []
for line in inputfile:
if line.find("patternB") != -1:
item = line.split()
dummy += item[0] + " xx " + item[-1] + "\n"
else:
dummy += line
outputfile.write(dummy)
The simplest will be:
1. Read all File into string
2. Call string.replace
3. Dump string to file
If you want to keep line by line iterator
(for a big file)
for line in inputfile:
if line.find("patternB") != -1:
dummy = line.replace('patternB', 'patternB xx oo')
outputfile.write(dummy)
else:
outputfile.write(line)
This is slower than other responses, but enables big file processing.
This should work
import os
def replace():
f1 = open("d:\myfile.abc","r")
f2 = open("d:\myfile_renew.abc","w")
ow = raw_input("Enter word you wish to replace:")
nw = raw_input("Enter new word:")
for line in f1:
templ = line.split()
for i in templ:
if i==ow:
f2.write(nw)
else:
f2.write(i)
f2.write('\n')
f1.close()
f2.close()
os.remove("d:\myfile.abc")
os.rename("d:\myfile_renew.abc","d:\myfile.abc")
replace()
You can use str.replace:
s = '''some lines
line contain patternA
some lines
line contain patternB
more lines'''
print(s.replace('patternB', 'patternB xx oo'))
Below is my code, the problem that I'm working on is to have the output of my program "written to a file whose name is obtained by appending the string _output to the input file name".
What is the correct way of going about doing this?
fileName = raw_input('Enter the HTML file name:') + '.html'
f = open(fileName, 'r')
myList = f.readlines()
for i in range(0, len(myList)):
toString = ''.join(myList)
newString = toString.replace('<span>', '')
newString = newString.replace('</span>', '')
print newString #testing the output
f.close()
Here is revised code. Something like this?
fileName = raw_input('Enter the HTML file name:') + '.html'
f = open(fileName, 'r')
fnew = open(fileName, 'w')
myList = f.readlines()
for i in range(0, len(myList)):
toString = ''.join(myList)
newString = toString.replace('<span>', '')
newString = newString.replace('</span>', '')
fnew.write(newString)
f.close()
Try;
fileName = raw_input('Enter the HTML file name:') + '.html'
f = open(fileName, 'r+')
toString = f.read()
newString = toString.replace('<span>', '')
newString = newString.replace('</span>', '')
print newString #testing the output
f.truncate() #clean all content from the file
f.write(newString) #write to the file
f.close()
Please refer this post : In Python, is read() , or readlines() faster?
If you want to print the output to a new file then;
new_file = open(new_file_path, 'w') #If the file does not exist, creates a new file for writing
new_file.write(newString)
new_file.close()
Now no need to open the first html file read/write use
f = open(fileName, 'r')