How to read each line in a file backwards using Python [duplicate] - python

This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed 3 years ago.
I'm trying to read a file (example below), line by line, backwards using Python.
abcd 23ad gh1 n d
gjds 23iu bsddfs ND31 NG
Note: I'm not trying to read the file from the end to the beginning, but I want to read each line starting from the end, i.e d for line 1, and NG for line 2.
I know that
with open (fileName) as f:
for line in f:
reads each line from left to right, I want to read it from right to left.

Try this:
with open(fileName, 'r') as f:
for line in f:
for item in line.split()[::-1]:
print(item)

If your file is not too big, you can read lines in reverse easily
with open(fileName) as f:
for line in reversed(f.readlines()):
# do something
Otherwise, I believe you'd have to use seed.

Related

How to delete the last 4 characters from every line in a file? - Python [duplicate]

This question already has answers here:
Is it possible to modify lines in a file in-place?
(5 answers)
Closed 2 years ago.
Can anyone give me some advice on creating a loop to cut the last 4 characters from every line within an input file?
I have tried:
myfile = open('delete.txt', 'w+')
myfile.read()
for line in myfile:
line = line[:3]
myfile.close()
The file is formatted like thi:
Awks,1er,xyz,lon,thr,tkj,,^M
Atks,1er,xyz,lon,thr,toj,,^M
Ahks,1er,xyz,lon,thr,taj,,^M
Auks,1er,xaz,lon,thr,tej,,^M
Aqks,1er,xyz,lon,thr,twj,,,^M
Aoks,1er,xaz,lon,thr,twj,,^M
Apks,1er,xwz,lon,thr,trj,,^M
Alks,1er,xuz,lon,thr,toe,,^M
ssks,1er,xoz,lon,thr,toj,,^M
ssks,1er,xnz,lon,thr,tog,,,^M
As some comments said, it's probably safer to open up the input file and write output to a separate file.
Using a with block is handy, because you don't need to handle closing a file; your file is automatically closed at the end of the block.
I'd do something like this:
with open('input.txt', 'r') as infile:
with open('output.txt', 'w') as outfile:
for line in infile:
outfile.write(line[:-5])
outfile.write('\n')
The line[:-5] will remove the last five characters of each line, which is probably what you want since each line also contains a newline, so it removes the newline and four characters. We outfile.write('\n') because the newline was removed, and we want it back.

Remove current line from file [duplicate]

This question already has answers here:
Is it possible to modify lines in a file in-place?
(5 answers)
Closed 2 years ago.
Consider a file with the following lines:
remove
keep
remove
Is it possible to remove the current line while iterating the file lines?
for word in file:
if word != "keep":
remove_line_from_file
In the end the file should just the line with word keep.
I know I could create a file with the remaining words but I was hoping to keep the same file.
Python has a nice library named fileinput which allows you to modify files inplace. You can print what you want to keep back into the file:
with fileinput.input(filename, inplace=True) as lines:
for line in lines:
if line == 'keep':
print(line,)
No, but you can extract all the contents of the file beforehand, modify the text, and then rewrite them back into the file:
with open('file.txt','r') as f:
lines = f.readlines()
with open('file.txt','w') as f:
f.write(''.join([ln for ln in lines if 'keep' in ln])) # Writes all the lines back to file.txt that has the word `keep` in them

print list line by line in python [duplicate]

This question already has answers here:
How to read a large file - line by line?
(11 answers)
Closed 4 years ago.
I am new in python and I am trying to print a list line by line.
fp = open(filepath) # Open file on read mode
lines = fp.read().split("\n") #Create a list with each line
print(lines) #Print the list
for line in lines:
print(line) #Print each line
fp.close()
But it's printing in one line.
The contents of the text file are
peat1,1,11345674565,04-11-2018
peat2,0,11345674565,05-11-2018
peat3,1,11345674565,06-11-2018
peat4,0,11345674565,07-11-2018
And it is printing as
peat1,1,11345674565,04-11-2018 peat2,0,11345674565,05-11-2018 peat3,1,11345674565,06-11-2018 peat4,0,11345674565,07-11-2018
The environment is -- Python 3.4 and running under Apache through cgi-bin
Any help is highly appreciated.
With large files, you are better off reading files line by line, like so:
with open('filename') as file:
for line in file:
print(line)
I suggest this approach with with, which handles closing the file pointer itself.

Pythons equivalent to PHP's file(fn, FILE_IGNORE_NEW_LINES) [duplicate]

This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 9 years ago.
I want to read a file in python and put each new line into an array. I know how to do it in PHP, with the file(fn, FILE_IGNORE_NEW_LINES); function and it's FILE_IGNORE_NEW_LINES parameter, but how do I do it in Python?
When reading a file (line-by-line), usually the new line characters are appended to the end of the line, as you loop through it. If you want to get rid of them?
with open('filename.txt', 'r') as f:
for line in f:
line = line.strip('\n')
#do things with the stripped line!
This is the same as (In Python):
with open("file.txt", "r") as f:
for line in f:
line = line.rstrip("\n")
...
You want this:
with open('filename.txt', 'r') as f:
data = [line.replace('\n', '') for line in f]

Search through file until no more data [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Reading huge data from files and calling them
I do not know how to search through a file, I have a file which has around 50 lines of data in this format (1.000 2.000 3.000) but I do not know how to do one line do a conversion(already have) then go to the next line do the same until it reaches the end, so basically do a process line by line until no more lines.
with open('filename') as f:
for line in f:
line = line.rstrip()
# do the conversion (that you already know how to do)
Here:
with open('filename') as f: opens the file (and automatically closes it at the end);
for line in f: reads every line of the file into line;
line = line.rstrip() removes any trailing whitespaces and the newline character from line.

Categories