Adding lines after specific line - python

I'm trying to add specific lines to a specific area in my file.
I am using this:
new_file = open("file.txt", "r+")
for line in new_file:
if line == "; Include below":
line = line + "\nIncluded text"
new_file.write(line)
else:
new_file.write(line)
But for some reason the content of my file.txt is duplicating.
Edit: If my file looks like:
blablablablablablabal
balablablabalablablbla
include below
blablablablablabalablab
ablablablabalbalablaba
I want make it look like:
blablablablablablabal
balablablabalablablbla
include below
included text
blablablablablabalablab
ablablablabalbalablaba

You cannot safely write to a file while reading, it is better to read the file into memory, update it, and rewrite it to file.
with open("file.txt", "r") as in_file:
buf = in_file.readlines()
with open("file.txt", "w") as out_file:
for line in buf:
if line == "; Include this text\n":
line = line + "Include below\n"
out_file.write(line)

This is what I did.
def find_append_to_file(filename, find, insert):
"""Find and append text in a file."""
with open(filename, 'r+') as file:
lines = file.read()
index = repr(lines).find(find) - 1
if index < 0:
raise ValueError("The text was not found in the file!")
len_found = len(find) - 1
old_lines = lines[index + len_found:]
file.seek(index)
file.write(insert)
file.write(old_lines)
# end find_append_to_file

Use sed:
$ sed '/^include below/aincluded text' < file.txt
Explanation:
/^include below/: matches every line that starts (^) with include below
a: appends a newline and the following text
includeed text: the text that a appends
Edit: Using Python:
for line in open("file.txt").readlines():
print(line, end="")
if line.startswith("include below"):
print("included text")

Related

Is there any idea of deleting lines in python?

So,I have this problem,the code below will delete the 3rd line in a text file.
with open("sample.txt","r") as f:
lines = f.readlines()
del lines[2]
with open("sample.txt", "w+") as f2:
for line in lines:
f2.write(line)
How to delete all lines from a text file?
Why use loop if you want to have an empty file anyways?
f = open("sample.txt", "r+")
f.seek(0)
f.truncate()
This will empty the content without deleting the file!
I think you to need something like this
import os
def delete_line(original_file, line_number):
""" Delete a line from a file at the given line number """
is_skipped = False
current_index = 1
dummy_file = original_file + '.bak'
# Open original file in read only mode and dummy file in write mode
with open(original_file, 'r') as read_obj, open(dummy_file, 'w') as write_obj:
# Line by line copy data from original file to dummy file
for line in read_obj:
# If current line number matches the given line number then skip copying
if current_index != line_number:
write_obj.write(line)
else:
is_skipped = True
current_index += 1
# If any line is skipped then rename dummy file as original file
if is_skipped:
os.remove(original_file)
os.rename(dummy_file, original_file)
else:
os.remove(dummy_file)

How can we write a text file from variable using python?

I am working on NLP project and have extracted the text from pdf using PyPDF2. Further, I removed the blank lines. Now, my output is being shown on the console but I want to populate the text file with the same data which is stored in my variable (file).
Below is the code which is removing the blank lines from a text file.
for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file=line
print(file)
Output on Console:
Eclipse,
Visual Studio 2012,
Arduino IDE,
Java
,
HTML,
CSS
2013
Excel
.
Now, I want the same data in my (resume1.txt) text file. I have used three methods but all these methods print a single dot in my resume1.txt file. If I see at the end of the text file then there is a dot which is being printed.
Method 1:
with open("resume1.txt", "w") as out_file:
out_file.write(file)
Method 2:
print(file, file=open("resume1.txt", 'w'))
Method 3:
pathlib.Path('resume1.txt').write_text(file)
Could you please be kind to assist me in populating the text file. Thank you for your cooperation.
First of all, note that you are writing to the same file losing the old data, I don't know if you want to do that. Other than that, every time you write using those methods, you are overwriting the data you previously wrote to the output file. So, if you want to use these methods, you must write just 1 time (write all the data).
SOLUTIONS
Using method 1:
to_file = []
for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
to_file.append(file)
to_save = '\n'.join(to_file)
with open("resume1.txt", "w") as out_file:
out_file.write(to_save)
Using method 2:
to_file = []
for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
to_file.append(file)
to_save = '\n'.join(to_file)
print(to_save, file=open("resume1.txt", 'w'))
Using method 3:
import pathlib
to_file = []
for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
to_file.append(file)
to_save = '\n'.join(to_file)
pathlib.Path('resume1.txt').write_text(to_save)
In these 3 methods, I have used to_save = '\n'.join(to_file) because I'm assuming you want to separate each line of other with an EOL, but if I'm wrong, you can just use ''.join(to_file) if you want not space, or ' '.join(to_file) if you want all the lines in a single one.
Other method
You can do this by using other file, let's say 'output.txt'.
out_file = open('output.txt', 'w')
for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
out_file.write(file)
out_file.write('\n') # EOL
out_file.close()
Also, you can do this (I prefer this):
with open('output.txt', 'w') as out_file:
for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
out_file.write(file)
out_file.write('\n') # EOL
First post on stack, so excuse the format
new_line = ""
for line in open('resume1.txt', "r"):
for char in line:
if char != " ":
new_line += char
print(new_line)
with open('resume1.txt', "w") as f:
f.write(new_line)

How to read line in text file and replace the whole line in Python?

I want to replace a whole line in a text document, if there is a line that begins with "truck_placement"
Can I remove the whole line when it contains "truck_placement" and then write the new text?
I tried it but it only inserts the new text und doesn't replace the whole line.
Thats the current code:
cordget = coordinatesentry.get()
fin = open(save_file,"r")
filedata = fin.read()
fin.close
newdata = filedata.replace("truck_placement: " , "truck_placement: " + cordget)
fin = open(save_file, "w")
fin.write(newdata)
fin.close
Your best bet is to append all the lines without "truck_placement" to a new file. This can be done with the following code:
original = open("truck.txt","r")
new = open("new_truck.txt","a")
for line in original:
if "truck_placement" not in line:
new.write(line)
original.close()
new.close()
You can either read the whole file into one string and replace the line using regular expression:
import re
cordget = "(value, one) (value, two)"
save_file = "sample.txt"
with open(save_file, "r") as f:
data = f.read()
# Catch the line from "truck_placement: " until the newline character ('\n')
# and replace it with the second argument, where '\1' the catched group
# "truck_placement: " is.
data = re.sub(r'(truck_placement: ).*\n', r'\1%s\n' % cordget, data)
with open(save_file, "w") as f:
f.writelines(data)
Or you could read the file as a list of all lines and overwrite the specific line:
cordget = "(value, one) (value, two)"
save_file = "sample.txt"
with open(save_file, "r") as f:
data = f.readlines()
for index, line in enumerate(data):
if "truck_placement" in line:
data[index] = f"truck_placement: {cordget}\n"
with open(save_file, "w") as f:
f.writelines(data)

How to erase line from text file in Python?

I'm trying to make a code to rewrite a specific line from a .txt file.
I can get to write in the line i want, but i can't erase the previous text on the line.
Here is my code:
(i'm trying a couple of things)
def writeline(file,n_line, text):
f=open(file,'r+')
count=0
for line in f:
count=count+1
if count==n_line :
f.write(line.replace(str(line),text))
#f.write('\r'+text)
You can use this code to make a test file for testing:
with open('writetest.txt','w') as f:
f.write('1 \n2 \n3 \n4 \n5')
writeline('writetest.txt',4,'This is the fourth line')
Edit: For Some reason, if i use 'if count==5:' the code compiles ok (even if it doen't erase the previous text), but if i do 'if count==n_line: ', the file ends up with a lot of garbage.
The Answers work, but i would like to know what are the problems with my code, and why i can't read and write. Thanks!
You are reading from the file and also writing to it. Don't do that. Instead, you should write to a NamedTemporaryFile and then rename it over the original file after you finish writing and close it.
Or if the size of the file is guaranteed to be small, you can use readlines() to read all of it, then close the file, modify the line you want, and write it back out:
def editline(file,n_line,text):
with open(file) as infile:
lines = infile.readlines()
lines[n_line] = text+' \n'
with open(file, 'w') as outfile:
outfile.writelines(lines)
Use temporary file:
import os
import shutil
def writeline(filename, n_line, text):
tmp_filename = filename + ".tmp"
count = 0
with open(tmp_filename, 'wt') as tmp:
with open(filename, 'rt') as src:
for line in src:
count += 1
if count == n_line:
line = line.replace(str(line), text + '\n')
tmp.write(line)
shutil.copy(tmp_filename, filename)
os.remove(tmp_filename)
def create_test(fname):
with open(fname,'w') as f:
f.write('1 \n2 \n3 \n4 \n5')
if __name__ == "__main__":
create_test('writetest.txt')
writeline('writetest.txt', 4, 'This is the fourth line')

Match the last word and delete the entire line

Input.txt File
12626232 : Bookmarks
1321121:
126262
Here 126262: can be anything text or digit, so basically will search for last word is : (colon) and delete the entire line
Output.txt File
12626232 : Bookmarks
My Code:
def function_example():
fn = 'input.txt'
f = open(fn)
output = []
for line in f:
if not ":" in line:
output.append(line)
f.close()
f = open(fn, 'w')
f.writelines(output)
f.close()
Problem: When I match with : it remove the entire line, but I just want to check if it is exist in the end of line and if it is end of the line then only remove the entire line.
Any suggestion will be appreciated. Thanks.
I saw as following but not sure how to use it in here
a = "abc here we go:"
print a[:-1]
I believe with this you should be able to achieve what you want.
with open(fname) as f:
lines = f.readlines()
for line in lines:
if not line.strip().endswith(':'):
print line
Here fname is the variable pointing to the file location.
You were almost there with your function. You were checking if : appears anywhere in the line, when you need to check if the line ends with it:
def function_example():
fn = 'input.txt'
f = open(fn)
output = []
for line in f:
if not line.strip().endswith(":"): # This is what you were missing
output.append(line)
f.close()
f = open(fn, 'w')
f.writelines(output)
f.close()
You could have also done if not line.strip()[:-1] == ':':, but endswith() is better suited for your use case.
Here is a compact way to do what you are doing above:
def function_example(infile, outfile, limiter=':'):
''' Filters all lines in :infile: that end in :limiter:
and writes the remaining lines to :outfile: '''
with open(infile) as in, open(outfile,'w') as out:
for line in in:
if not line.strip().endswith(limiter):
out.write(line)
The with statement creates a context and automatically closes files when the block ends.
To search if the last letter is : Do following
if line.strip().endswith(':'):
...Do Something...
You can use a regular expression
import re
#Something end with ':'
regex = re.compile('.(:+)')
new_lines = []
file_name = "path_to_file"
with open(file_name) as _file:
lines = _file.readlines()
new_lines = [line for line in lines if regex.search(line.strip())]
with open(file_name, "w") as _file:
_file.writelines(new_lines)

Categories

Resources