I want to append some text to every line in my file
Here is my code
filepath = 'hole.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
#..........
#want to append text "#" in every line by reading line by line
text from .txt file
line = fp.readline()
cnt += 1
You can read the lines and put them in a list. Then you open the same file with write mode and write each line with the string you want to append.
filepath = "hole.txt"
with open(filepath) as fp:
lines = fp.read().splitlines()
with open(filepath, "w") as fp:
for line in lines:
print(line + "#", file=fp)
Assuming you can load the full text in memory, you could open the file, split by row and for each row append the '#'. Then save :-) :
with open(filepath, 'r') as f: # load file
lines = f.read().splitlines() # read lines
with open('new_file.txt', 'w') as f:
f.write('\n'.join([line + '#' for line in lines])) # write lines with '#' appended
I'll assume the file is small enough to keep two copies of it in memory:
filepath = 'hole.txt'
with open(filepath, 'r') as f:
original_lines = f.readlines()
new_lines = [line.strip() + "#\n" for line in original_lines]
with open(filepath, 'w') as f:
f.writelines(new_lines)
First, we open the file and read all lines into a list. Then, a new list is generated by strip()ing the line terminators from each line, adding some additional text and a new line terminator after it.
Then, the last line overwrites the file with the new, modified lines.
does this help?
inputFile = "path-to-input-file/a.txt"
outputFile = "path-to-output-file/b.txt"
stringToAPpend = "#"
with open(inputFile, 'r') as inFile, open(outputFile, 'w') as outFile:
for line in inFile:
outFile.write(stringToAPpend+line)
Related
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)
line_row = -1
file = open(file_path, 'r')
for number_of_lines in file:
line_row = line_row + 1
if '1234' in number_of_lines:
lines = file.readlines()
line = lines[line_row]
print(lines)
lines[line_row] = 'hello'
file = open(file_path, "w")
file.writelines(lines)
file.close()
When I run this, it will delete everything that is before the nth line. I want it to replace only the nth line. can you help me?
try this, using enumerate
with open(file_path, 'r') as f:
lines = f.readlines()
for i, line in enumerate(lines):
if "some text" in line:
lines[i] = "updated text"
with open(file_path, "w") as f:
f.writelines(lines)
Text file contains below data:
InitialSearch='Searched data'
file = open("textfile.txt","r")
lines = file.readlines()
file.close()
fileOutput = open ('NewTextFile.txt', 'w')
for x,line in enumerate(lines):
if line.find(InitialSearch)>=0:
fileOutput.write(line)
fileOutput.close
Code is not properly working
You already have the index of the "matched" line in your for loop. Just add two to it, and you will have the row you want to add to the output file.
InitialSearch='Searched data'
file = open("textfile.txt","r")
lines = file.readlines()
file.close()
with open('NewTextFile.txt', 'w') as fileOutput
for x,line in enumerate(lines):
if line.find(InitialSearch)>=0:
fileOutput.write(lines[x+2])
my objective is to check the file and see if the last line is a newline(empty) and if so delete it. I've tried heaps of methods like this and etc:
for filename in os.listdir(directory):
if filename.endswith(".ADC"):
with open(os.path.join(directory, filename)) as infile, open(os.path.join(directory, filename)) as outfile:
lines = infile.readlines()
if lines:
lines[-1] = lines[-1].rstrip('\r\n')
infile.writelines(lines)
also tried the readlines method with no success.
try this:
for filename in os.listdir(directory):
if filename.endswith(".ADC"):
with open(os.path.join(directory, filename), "r") as f:
lines = f.readlines()
for line in lines[::-1]:
if line == '\n' or line == '\r':
lines = lines[:-1]
print(lines)
Check if the last line is an empty string. If it is, calculate the total size of the preceding lines, and then truncate the file to that size.
for filename in os.listdir(directory):
if filename.endswith(".ADC"):
with open(os.path.join(directory, filename), "r") as file:
lines = file.readlines()
if lines and lines[-1].rstrip('\r\n') == "":
lines.pop()
size = sum(len(l) for l in lines)
file.truncate(size)
Truncating is more efficient than rewriting the whole file without the last line.
I have a file txt, where there are severals lines... Some of these are links. My question is: How can I catch all this links and save them on another txt file? I'm a newbie.
I tried with this but it doesn't work:
filee = open("myfile.txt").readlines()
out_file = open("out.txt","w")
out_file.write("")
out_file.close()
for x in filee:
if x.startswith("http"):
out_file.write(x)
print (x)
You can't write to a closed file. Just move the out_file.close() at the end of your code:
filee = open("myfile.txt").readlines()
out_file = open("out.txt","w")
out_file.write("")
for x in filee:
if x.startswith("http"):
out_file.write(x)
print (x)
out_file.close()
Here a cleaner version:
# open the input file (with auto close)
with open("myfile.txt") as input_file:
# open the output file (with auto close)
with open("out.txt", "w") as output_file:
# for each line of the file
for line in input_file:
# append the line to the output file if start with "http"
if line.startswith("http"):
output_file.write(line)
You can also combine the two with:
# open the input/output files (with auto close)
with open("myfile.txt") as input_file, open("out.txt", "w") as output_file:
# for each line of the file
for line in input_file:
# append the line to the output file if start with "http"
if line.startswith("http"):
output_file.write(line)