Prepend line number to string in python - python

I have a text file in the following format:
"This is record #1"
"This is record #2"
"This is record #3"
I need the output in the following format:
Line number (1) --\t-- "This is Record # 1"
2-- \t-- "This is Record # 2"
3-- \t-- "This is Record # 3"
Current code:
f = open("C:\input.txt","r")
write_file = open("C:\output.txt","r+")
while True:
line = f.readline()
write_file.write(line)
if not line : break
write_file.close()
f.close()

Try traversing your file this way:
f = open('workfile', 'r')
for num,line in enumerate(f):
print(num+" "+line)

Your code was pretty close to the target:
# open the file for reading
f = open("C:\input.txt","r")
# and a file for writing
write_file = open("C:\output.txt","r+")
for i, line in enumerate(f):
line = f.readline()
mod_line = "%s-- \t-- %s" % (i, line) # 1-- \t-- "This is Record # 1"
write_file.write(mod_line)
write_file.close()
f.close()

Related

Lines missing in python

I am writing a code in python where I am removing all the text after a specific word but in output lines are missing. I have a text file in unicode which have 3 lines:
my name is test1
my name is
my name is test 2
What I want is to remove text after word "test" so I could get the output as below
my name is test
my name is
my name is test
I have written a code but it does the task but also removes the second line "my name is"
My code is below
txt = ""
with open(r"test.txt", 'r') as fp:
for line in fp.readlines():
splitStr = "test"
index = line.find(splitStr)
if index > 0:
txt += line[:index + len(splitStr)] + "\n"
with open(r"test.txt", "w") as fp:
fp.write(txt)
It looks like if there is no keyword found the index become -1.
So you are avoiding the lines w/o keyword.
I would modify your if by adding the condition as follows:
txt = ""
with open(r"test.txt", 'r') as fp:
for line in fp.readlines():
splitStr = "test"
index = line.find(splitStr)
if index > 0:
txt += line[:index + len(splitStr)] + "\n"
elif index < 0:
txt += line
with open(r"test.txt", "w") as fp:
fp.write(txt)
No need to add \n because the line already contains it.
Your code does not append the line if the splitStr is not defined.
txt = ""
with open(r"test.txt", 'r') as fp:
for line in fp.readlines():
splitStr = "test"
index = line.find(splitStr)
if index != -1:
txt += line[:index + len(splitStr)] + "\n"
else:
txt += line
with open(r"test.txt", "w") as fp:
fp.write(txt)
In my solution I simulate the input file via io.StringIO. Compared to your code my solution remove the else branch and only use one += operater. Also splitStr is set only one time and not on each iteration. This makes the code more clear and reduces possible errore sources.
import io
# simulates a file for this example
the_file = io.StringIO("""my name is test1
my name is
my name is test 2""")
txt = ""
splitStr = "test"
with the_file as fp:
# each line
for line in fp.readlines():
# cut somoething?
if splitStr in line:
# find index
index = line.find(splitStr)
# cut after 'splitStr' and add newline
line = line[:index + len(splitStr)] + "\n"
# append line to output
txt += line
print(txt)
When handling with files in Python 3 it is recommended to use pathlib for that like this.
import pathlib
file_path = pathlib.Path("test.txt")
# read from wile
with file_path.open('r') as fp:
# do something
# write back to the file
with file_path.open('w') as fp:
# do something
Suggestion:
for line in fp.readlines():
i = line.find('test')
if i != -1:
line = line[:i]

How to completely delete the first line of a text file?

I have a script that outputs a text file (Mod_From_SCRSTXT.txt). I need to delete the first line of that file.
I have tried changing the last line of the find function shown below. The first line still get printed in the new file created even with the changes.
def find(substr, infile, outfile):
with open(infile) as a, open(outfile, 'a') as b:
for line in a:
if substr in line:
b.write(line[1:])
srcn_path1 = input(" Enter Path. Example: U:\...\...\SRCNx\SCRS.TXT\n" +
" Enter SRCS.TXT's Path: ")
print ()
scrNumber1 = input(' Enter SCR number: ')
print ()
def find(substr, infile, outfile):
with open(infile) as a, open(outfile, 'a') as b:
for line in a:
if substr in line:
b.write(line) # or (line + '\n')
# action station:
find(scrNumber1, srcn_path1, 'Mod_From_SCRSTXT.txt')
Actual result:
VSOAU-0004 16999
VSOAU-0004
VSOAU-0004
VSOAU-0004
VSOAU-0004
Expected result:
VSOAU-0004
VSOAU-0004
VSOAU-0004
VSOAU-0004
You'll want to make a minor adjustment:
You can either count the lines in the file:
numberOfLines = 0
for line in file:
numberOfLines += 1
for line in range(1, linesInFile + 1):
Or you can ignore the first line through many different ways, this being a simple one:
ignoredLine = 0
for line in file:
if not ignoredLine:
ignoredLine = 1
else:
#Do stuff with the other lines
import pathlib
import os
import copy
import io
def delete_first_line(read_path):
try:
read_path = pathlib.Path(str(read_path))
write_path = str(copy.copy(read_path)) + ".temp"
while os.path.exists(write_path):
write_path = write_path + ".temp"
with open(read_path , mode = "r") as inf:
with open(write_path, mode="w") as outf:
it_inf = iter(inf)
next(it_inf) # discard first line
for line in it_inf:
print(line, file = outf)
os.remove(read_path)
os.rename(write_path, read_path)
except StopIteration:
with io.StringIO() as string_stream:
print(
"Cannot remove first line from an empty file",
read_path,
file = string_stream,
sep = "\n"
)
msg = string_stream.getvalue()
raise ValueError(msg)
except FileNotFoundError:
with io.StringIO() as string_stream:
print(
"Cannot remove first line from non-existant file",
read_path,
file = string_stream,
sep = "\n"
)
msg = string_stream.getvalue()
raise ValueError(msg)
finally:
pass
return

Error trying to add lines to txt

I can't make my code work.
I open the file with r+ attribute, print what's already in it, take 2 lines from the user, but cannot write these files:
file1 = open('test.txt', 'r+')
print "\n This is your file:\n"
print file1.read()
print "Now type in 2 lines:"
line1 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")
print "Writing the lines"
file1.write(line1)
file1.write("\n")
file1.write(line2)
file1.write("\n")
print "\n This is your file again:\n"
print file1.read()
file1.close()
All I get is:
Traceback (most recent call last):
File "C:/Python27/new.py", line 10, in
file1.write(line1)
IOError: [Errno 0] Error
Tested code:
def func():
with open('E:/test.txt', 'r') as f:
print f.read()
print "Now write 2 lines."
l1 = raw_input("Line 1: ")
l2 = raw_input("Line 2: ")
with open('E:/test.txt', 'a') as f:
f.write(l1 + "\n" + l2 + "\n")
with open('E:/test.txt', 'r') as f:
print ("This is your file now:\n" +
f.read())
Output:
>>> func()
hey
therecoolguy
Now write 2 lines.
Line 1: cool
Line 2: guy
This is your file now:
hey
there
cool
guy
Assumes you have a \n at end of the file but that's the only condition.
Recommend you read this for more python file IO modes.
after you read and write the lines, you cannot do file1.read() again because you are starting that from the end of the file!
your last 3 lines should look like this:
file1.seek(0) # go back to the start of the file
print file1.read()
file1.close()
but even more recommended is that you read and write on separate occasions, try this code:
with open('file1.txt') as f:
print f.read()
print 'Now write 2 lines'
line1 = raw_input('line1:')
line2 = raw_input('line2:')
print 'Writing lines'
with open('file1.txt','a') as f:
f.write(line1 + '\n' + line2 + '\n')
with open('file1.txt') as f:
print 'This is your file again:'
print f.read()

find a matching line in a txt with python

I can test whether a string is in a text file with python like the following:
if(pdfname in open(filename).read()):
//do something
But how I can I verify it? I want the matching line show up. Thanks.
You can print out the relevant lines with the second for statement below, which I've added to your existing code for illustration:
pdfname = "statementConcentrator"
if (pdfname in open("line56.good").read()):
print "Found it"
lineNum = 0
for line in open("line56.good").readlines():
lineNum = lineNum + 1
if pdfname in line:
print "#%5d: %s"%(lineNum, line[:-1])
This outputs your current line plus my output for verification:
Found it
# 115: statementConcentrator=0
and, checking that file, that is indeed the line it's found on.
Note that you can simply use a script as follows to do both jobs in a single loop:
pdfname = "statementConcentrator"
lineNum = 0
count = 0
for line in open("line56.good").readlines():
lineNum = lineNum + 1
if pdfname in line:
print "#%5d: %s"%(lineNum, line[:-1])
count = count + 1
print "Found on %d line(s)."%(count)
Just loop over the file:
handle = open(filename, 'r')
for line in handle:
if pdfname in line:
print line
handle.close()

How to change back a line during file read

In my code I have a line length print like this:
line = file.readline()
print("length = ", len(line))
after that I start to scan the lines by doing this:
for i in range(len(line)):
if(file.read(1) == 'b'):
print("letter 'b' found.")
The problem is that the for loop starts reading on line 2 of the file.
How can I make it start reading at line 1 without closing and reopening the file?
It is possible to use file.seek to move the position of the next read, but that's inefficient. You've already read in the line, so you can just process
line without having to read it in a second time.
with open(filename,'r') as f:
line = f.readline()
print("length = ", len(line))
if 'b' in line:
print("letter 'b' found.")
for line in f:
...
It seems that you need to handle the first line specially.
lineno = 1
found = False
for line in file:
if 'b' in line:
found = True
if lineno == 1:
print("length of first line: %d" % len(line))
lineno += 1
if found:
print("letter 'b' found.")
It sounds like you want something like this:
with open('file.txt', 'r') as f:
for line in f:
for character in line:
if character == "b":
print "letter 'b' found."
or if you just need the number:
with open('file.txt', 'r') as f:
b = sum(1 for line in f for char in line if char == "b")
print "found %d b" % b
#! usr/bin/env python
#Open the file , i assumed its called somefile.txt
file = open('somefile.txt.txt','r')
#Lets loop through the lines ...
for line in file.readlines():
#test if letter 'b' is in each line ...
if 'b' in line:
#print that we found a b in the line
print "letter b found"

Categories