python3 replace a empty line with fileinput - python-3.x

I have a file that has empty line between each line like this:
line one
line two
line three
I want to append a line after line two
This is how I am trying to do it
for line_num, line in enumerate(fileinput.FileInput(file, inplace=1) ):
if line_num == 4:
line.replace(" ", 'line to append')
The problem with this is it overwrites the entire file when I want to append the line

Your approach has a few (small) issues.
you do not print the lines to the file
line_num == 4 will not write after line two, unless you use enumerate with start=1
(assuming that you want to fill an empty line) line.replace(' ', 'line to append') will not do the trick because an empty line does contain a space
Try:
>>> import fileinput
>>> with fileinput.input('test', inplace=True) as f:
... for line_num, line in enumerate(f):
... if line_num == 3 and line in ['\n', '\r\n']:
... line = 'line to append\n'
... print(line, end='')
...
test had originally the content in your description and after:
$ cat test
line one
line two
line to append
line three
line_num == 3 and line in ['\n', '\r\n'] says "find the 4th line and check if it is empty". You may want to update/replace the checks based on your needs.

Related

Receursivley read lines of a file

I want to read specific lines of a file each time I run the program.
Say a text file has
line 1
line 2
line 3
line 4
line 5
line 6
I would like to read every third line of the file, every time I run it.
with open("test.txt", "r+") as f:
for line in f:
line = f.readline()
#do something with line
The above code only reads the first line or it just picks which line to read and I want to be specific. Every third line.
Enumerate does allow for me to read the specific lines but evaluating them one by one is the problem thereafter.
How do I do it?
Here is an example:
def _read(file, step, start=0):
with open(file, "r") as f:
for line in f.readlines()[start::step]:
print(line.strip())
_read('test.txt', 3, 2)
Output:
line 3
line 6
line 9
Here is with class:
class Reader:
def __init__(self, file_name, mode='r', start=0, step=1):
self.file = open(file_name, mode)
self.lines = self.file.readlines()[start::step]
self.file.close()
def get_line(self):
if self.lines:
return self.lines.pop(0).strip()
else:
print('No more lines')
r = Reader('test.txt', start=2, step=3)
print(r.get_line())
print(r.get_line())
print(r.get_line())
print(r.get_line())
print(r.get_line())
Output:
line 3
line 6
line 9
No more lines
None
No more lines
None

Writing python scripts

I need to write a standalone program that would run on a python cmd. This program counts the number of characters in every line of HumptyDumpty.txt file, and outputs this to a new file.
Note that the new file needs to contain only the number of characters per line.
Here's my code:
import sys
infilename = sys.argv[1]
outfilename = sys.argv[2]
infile=open(infilename)
outfile=open(outfilename, 'w')
char_=0
for line in infile:
line.split()
char_= len(line.strip("\n"))
outfile.write(str(char_ ))
print(line,end='')
infile.close()
outfile.close()
The ouput file has only one line, the concatenation of xyz instead of
x
y
z
"\n" doesnt seem to be doing the trick. Any suggestions?
If you don't want to include the white space between the words then you should replace them with an empty string.
for line in infile:
nline = line.replace(" ", "")
nline = nline.strip("\n")
char= len(nline)
outfile.write(str(char))
outfile.write("\n")
print(line, end='')
print(char)

keep order as it was saved and keep only unique words in text file list

need sort lines in order in which they were saved in txt file, just new line comes from below and save this order after remove similar words. so if I add words in loop one by one
line A
line B
line C
line D
line E
here I got three solutions, but nothing works for me correct
first keeps only unique words;
with open('C:\my_path\doc.txt', 'r') as lines:
lines_set = {line.strip() for line in lines}
with open(''D:\path\file.txt', 'w') as out:
for line in lines_set:
out.write(line + '\n')
but destroys order:
1. line B
2. line E
3. line C
4. line D
5. line A
second keeps order but same words too:
with open('C:\my_path\doc.txt', 'r') as lines:
lines_set = []
for line in lines:
if line.strip() not in lines_set:
lines_set.append(line.strip())
last one works well, but with input text:
with open('C:\my_path\doc.txt', 'r') as lines:
lines_set = []
for line in lines:
if line.strip() not in lines_set:
lines_set.append(line.strip())
in some cases I have no any input, and also have different input, so need somehow sort ordered list itself
can you help me figure out with it please
loadLines is almost as your function you show twice, but it allows duplicates. removeDuplicates strips duplicates. saveLines writes a list to a file, deliminating by newline. All functions preserve order.
#Load lines with duplicates
def loadLines(f):
with open(f, 'r') as lines:
lines_set = []
for line in lines:
lines_set.append(line.strip())
return lines_set
#Search list "l", return list without duplicates.
def removeDuplicates(l):
out = list(set(l))
for i in enumerate(out):
out[i[0]] = l.index(i[1])
out.sort()
for i in enumerate(out):
out[i[0]] = l[i[1]]
return out
#Write the lines "l" to filepath "f"
def saveLines(f, l):
open(f, 'w').write('\n'.join(l))
lines = loadLines('doc.txt')
print(lines)
stripped_lines = removeDuplicates(lines)
print(stripped_lines)
saveLines('doc.txt', stripped_lines)

How to avoid IndexError: list index out of range for previous or next line

I have a text file with lines, in order:
line 1
line 2
line 3
line 4
line 5
Now for example, if line 4 exist in the text file, I need to display the previous or next word relative to line 4 in order: previous is line 3 next is line 5
data = open('file.txt', "r")
searchlines = data.readlines()
for q_numb, line in enumerate(searchlines):
if ('line 4') in line:
prev_line = searchlines[q_numb - 1]
print ('"line 4" is found:',line, 'previous of "line 4" is:',prev_line)
break
data.close()
How do I avoid IndexError: list index out of range if [q_numb - 1] or [q_numb + 1] comes to an non-existent line? Should I just tell it to do something else, maybe somehow predict it? But how do I do that, how do I know to do something else if - or +1 comes to a non-existent line? (For example, read only the current line in this case).
The key is to check if the index of the current line i is always more than 0 and less than the length of the file, so at any time there is always a previous line and the next one.
with open('file.txt', 'r') as f:
lines = f.readlines()
for i, line in enumerate(lines):
if 'line 3' in line and 0 < i < len(lines):
print(lines[i - 1], line, lines[i + 1])
This will prints out the previous, the current and the next line for 'line 2', 'line 3' and 'line 4' and ignore 'line 1' and 'line 5' which do not have a previous and next line to print.
Also, use with as an idiomatic way to open a resource with implicit close.
Use an if statement:
data = open('file.txt', "r")
searchlines = data.readlines()
lines_len = len(searchlines)
for q_numb, line in enumerate(searchlines):
if ('line 4') in line && 0 < q_numb < lines_len: #Here
prev_line = searchlines[q_numb - 1]
print ('"line 4" is found:',line, 'previous of "line 4" is:',prev_line)
break
data.close()

How to print select lines of a text file in python?

I have a text file with multiple lines of text. Each line of text is split into two columns, separated by a comma. How do I write a program to print only the lines of the text file that have a specific value for the first column? So for example how do I write a program to print every line that has "hello" as the first column?
I'm using python 3.3.3
#!/usr/bin/env python3
import sys
filename = sys.argv[1]
# read the file line by line
with open(filename) as f:
for line in f:
# split the line
columns = line.split(",")
# print all lines with "hello" as the first column
if columns[0] == "hello":
print(line, end='')

Resources