I need to add string after a word in a specific line of a text file. The original file is:
line 1: value1
line 2: value2
line 3: value3
line 4: value4
line 5: value5
For example, I want to add "NAME" in the line number 3 just after "line" so the file would become:
line 1: value1
line 2: value2
line NAME 3: value3
line 4: value4
line 5: value5
How would you do it?
with open(file, 'r') as f:
lines = []
for line in f:
split_lines = line.split(':')
if split_lines[0].endswith('3') is True:
lines.append(split_lines[0][:-1] + NAME + split_lines[1:])
else:
lines.append(line)
I would consider this:
line_number = 3#I understood you know this. right ?
string_to_add = "NAME"#I understood you know this. right ?
string_to_find = "line"#I understood you know this. right ?
filename = "toto"
with open(filename,"r") as f:
s = f.readlines()
s[line_number] = s[line_number].replace(string_to_find,string_to_find+string_to_add)
with open(filename,"w") as f:
for line in s:
f.write(line)
It's true that it seems highly inefficient (and probably not realistic for a large file). I would be curious to see better ways.
This looks for line that starts with “line 3:” and edits just this line, retains the rest as is, and writes the text to a new file.
with open('f1.txt', 'r') as f:
lines = []
for line in f:
if line.startswith("line 3:"):
split_line = line.split()
split_line.insert(split_line.index("3:"), "NAME")
lines.append(' '.join(split_line) + '\n')
else:
lines.append(line)
with open('f2.txt', 'w') as f:
for line in lines:
f.write(line)
When you run the code below,
with open('f2.txt', 'r') as f:
for line in f:
print(line, end='')
It prints:
line 1: value1
line 2: value2
line NAME 3: value3
line 4: value4
line 5: value5
Firebase Cloud Functions: PubSub, "res.on is not a function"
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
I'm trying to traverse an ftp directory using FTPwalker, however I cannot connect
I am trying to use the BeautifulSoup library in Python to extract the jpg image names from a html scriptIn the url wherever you find srcset it is always proceeded by a jpg file name
I try to connect mongodb database using mongoengine with dynamic connectioni getting database name from URL Request