Python - Deleting the last line if it is a newline - python

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.

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)

Append String to each line of .txt file in python?

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)

Remove the last empty line from each text file

I have many text files, and each of them has a empty line at the end. My scripts did not seem to remove them. Can anyone help please?
# python 2.7
import os
import sys
import re
filedir = 'F:/WF/'
dir = os.listdir(filedir)
for filename in dir:
if 'ABC' in filename:
filepath = os.path.join(filedir,filename)
all_file = open(filepath,'r')
lines = all_file.readlines()
output = 'F:/WF/new/' + filename
# Read in each row and parse out components
for line in lines:
# Weed out blank lines
line = filter(lambda x: not x.isspace(), lines)
# Write to the new directory
f = open(output,'w')
f.writelines(line)
f.close()
You can use Python's rstrip() function to do this as follows:
filename = "test.txt"
with open(filename) as f_input:
data = f_input.read().rstrip('\n')
with open(filename, 'w') as f_output:
f_output.write(data)
This will remove all empty lines from the end of the file. It will not change the file if there are no empty lines.
you can remove last empty line by using:
with open(filepath, 'r') as f:
data = f.read()
with open(output, 'w') as w:
w.write(data[:-1])
You can try this without using the re module:
filedir = 'F:/WF/'
dir = os.listdir(filedir)
for filename in dir:
if 'ABC' in filename:
filepath = os.path.join(filedir,filename)
f = open(filepath).readlines()
new_file = open(filepath, 'w')
new_file.write('')
for i in f[:-1]:
new_file.write(i)
new_file.close()
For each filepath, the code opens the file, reads in its contents line by line, then writes over the file, and lastly writes the contents of f to the file, except for the last element in f, which is the empty line.
You can remove the last blank line by the following command. This worked for me:
file = open(file_path_src,'r')
lines = file.read()
with open(file_path_dst,'w') as f:
for indx, line in enumerate(lines):
f.write(line)
if indx != len(lines) - 1:
f.write('\n')
i think this should work fine
new_file.write(f[:-1])

Python importing files - for loops

I have two simple files that I want to open in python and based on a keyword print information in the file
file a.txt contains:
'Final
This is ready'
file b.txt contains:
'Draft
This is not ready'
I want to read these two files in and if the file reads 'Final' anywhere in the txt file to print out the rest of the text (excluding the word 'Final'). My for loop is not outputting correctly:
fileList = ['a.txt','b.txt']
firstLineCheck = 'Final\n'
for filepath in fileList:
f = open(filepath, 'r') #openfiles
for line in f:
if line == firstLineCheck:
print line
else:
break
I feel like this is something simple - appreciate the help
fileList = ['a.txt', 'b.txt']
firstLineCheck = 'Final\n'
for filepath in fileList:
with open(filepath, 'r') as f:
line = f.readline()
while line:
if line == firstLineCheck:
print f.read()
line = f.readline()
There are three faults in your code. First you will only print lines that match and second is that you trigger only on lines that contains only "Final", third it does not exclude the line containing "Final" as specified. The fix would be to use a flag to see if you found the "Final":
fileList = ['a.txt','b.txt']
firstLineCheck = 'Final'
firstLineFound = False
for filepath in fileList:
f = open(filepath, 'r') #openfiles
for line in f:
if firstLineFound:
print line
elif firstLineCheck in line:
# print line # uncomment if you want to include the final-line
firstLineFound = True
else:
break
if you wanted to trigger only on lines containing only "Final" then you should instead use firstLineCheck = "Final\n" and elif line==firstLineCheck.
Assuming you want to print all lines starting a line that has only your firstLineCheck in it, and using your code ....
fileList = ['a.txt','b.txt']
firstLineCheck = 'Final\n'
for filepath in fileList:
f = open(filepath, 'r') #openfiles
do_print = False
for line in f:
if line == firstLineCheck:
do_print = True
continue
if do_print:
print line
Note that break takes you out of the loop, and continue will move to the next iteration.
Assuming your keyword is the first line of the file, you can do this. This makes more sense as you could have the word "Final" somewhere in the content of "draft".
fileList = ['a.txt','b.txt']
firstLineCheck = 'Final\n'
for filepath in fileList:
with open(filepath, 'r') as f:
first_line = f.readline() # read the first line
if first_line == firstLineCheck:
print f.read()
Since you wanted to check if Final was present in the first line you could read the file as a list and see if first element contains final if so prints the entire file except first line
fileList = ['a.txt','b.txt']
firstLineCheck = 'Final'
for filepath in fileList:
f = open(filepath, 'r').readlines() #openfiles
if firstLineCheck in f[0]:
print "".join(f[1:])
output:
This is ready'

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