How to generate an index for a file? - python

For instance if a file has
xxx|12
yyy|13
zzz|14
I need the output to be
1 xxx|12
2 yyy|13
3 zzz|14
How can I achieve that?

import fileinput
f=fileinput.FileInput("file",inplace=1)
for line in f:
print f.lineno(), line
there are many other ways to do it. If you are on a linux/unix system
awk '{print NR,$0}' file
cat -n file
sed '=' file
nl file
Also Ruby(1.9+)
ruby -ne 'print "#{$.} #{$_}"' file

inputfile = open('filein.txt', 'r')
outputfile = open('fileout.txt', 'w')
count = 1
for line in inputfile:
outputfile.write(str(count) + " " + line)
count += 1
outputfile.close()
inputfile.close()
et voile.

inputfile = open('filein.txt', 'r')
outputfile = open('fileout.txt', 'w')
for index, line in enumerate(inputfile, 1):
outputfile.write("%d %s" %(index, line))
outputfile.close()
inputfile.close()

I noticed that your input had some empty lines, anyway here you go:
text=open('input.txt','r')
lines=text.readlines()
text.close()
output=open('output.txt','w')
for lineNumber in range(len(lines)):
if lines[lineNumber] not in ["","\n","\t"]:
output.write(str(lineNumber)+" "+lines[lineNumber])
else:
output.write(lines[lineNumber])

Use enumerate().
f = open('input_file')
data = f.read().split()
f.close()
data = ["%d %s" % (idx + 1, x) for idx, x in enumerate(data)]
data = " ".join(data)
f = open('output_file', 'w')
f.write(data)
f.close()

Related

Python - Problem in appending lines to output file with specific condition

My Problem is the following:
I have a file with lines that normally start with 'ab', condition is when line not start with ab it should be appended to previous line, but some lines are not get appended to output file
Source File:
grpid;UserGroup;Name;Description;Owner;Visibility;Members -> heading
ab;user1;name1;des1;bhalji;public
sss
ddd
fff
ab;user2;name2;des2;bhalji;private -> not appended in output
ab;user3;name3;des3;bhalji;public -> not appended in output
ab;user4;name4;des4;bhalji;private
rrr
ttt
yyy
uuu
ab;user5;name5;des5;bhalji;private
ttt
ooo
ppp
Here's is what I'm doing using python:
def grouping():
output = []
temp = []
currIdLine = ""
with( open ('usergroups.csv', 'r')) as f:
for lines in f.readlines():
line = lines.strip()
if not line:
print("Skipping empty line")
continue
if line.startswith('grpid'):
output.append(line)
continue
if line.startswith('ab'):
if temp:
output.append(currIdLine + ";" + ','.join(temp))
temp.clear()
currIdLine = line
else:
temp.append(line)
output.append(currIdLine + ";" + ','.join(temp))
#print("\n".join(output))
with open('new.csv', 'w') as f1:
for row in output:
f1.write(row + '\n')
grouping ()
Output of the above code:
grpid;UserGroup;Name;Description;Owner;Visibility;Members
ab;user1;name1;des1;bhalji;public;sss,ddd,fff
ab;user4;name4;des4;bhalji;private;rrr,ttt,yyy,uuu
ab;user5;name5;des5;bhalji;private;ttt,ooo,ppp
I hope this should be quite easy with Python but I'm not getting it right so far.
That's how the file should look at the end:
Expected Output:
grpid;UserGroup;Name;Description;Owner;Visibility;Members
ab;user1;name1;des1;bhalji;public;sss,ddd,fff
ab;user2;name2;des2;bhalji;private
ab;user3;name3;des3;bhalji;public
ab;user4;name4;des4;bhalji;private;rrr,ttt,yyy,uuu
ab;user5;name5;des5;bhalji;private;ttt,ooo,ppp
You are close. Missing an else statement to deal with the case that the line starts with ab, and the previous line started with ab.
def grouping():
output = []
temp = []
currIdLine = ""
with(open('usergroups.csv', 'r')) as f:
header = f.readline()
output.append(line.strip())
temp = []
for line in f.readlines():
if not line:
print("Skipping empty line")
continue
if line.startswith('ab'):
if temp:
output.append(currIdLine + ";" + ','.join(temp))
temp = []
else:
output.append(currIdLine)
currIdLine = line.strip()
else:
temp.append(line.strip())
if temp:
output.append(currIdLine + ";" + ','.join(temp))
else: # <-- this block is needed
output.append(currIdLine)
with open('new.csv', 'w') as f1:
for row in output:
f1.write(row + '\n')

Simple math addition

so I just want to do some simple math addition
get number from the first file ( let's say it's 1)
and number from the second file ( let's say it's 2)
so what I'm getting is 12, not 3
I would really appreciate the help.
myfile = open('file.txt', "r")
onecaracter = myfile.read(2)
with open('liczba1.txt', 'w') as f:
print(onecaracter, file=f)
myfile = open('file.txt', "r")
twocaracter = myfile.read(myfile.seek(4))
with open('liczba22.txt', 'w') as f:
print(twocaracter, file=f)
with open('liczba1.txt', "r") as file:
z = file.read(1)
with open('liczba22.txt', "r") as fil:
b = fil.read(1)
print(z + b)
The variables z and b are likely str types, and the + operator is defined on str types as concatenation. You can cast the two variables as integers and they should add as you expect, i.e.:
print(int(z) + int(b))
To illustrate this, you can always print out the type of a variable:
print(type(z))
myfile = open('file.txt', "r")
onecaracter = myfile.read(2)
with open('liczba1.txt', 'w') as f:
print(onecaracter, file=f)
myfile = open('file.txt', "r")
twocaracter = myfile.read(myfile.seek(4))
with open('liczba22.txt', 'w') as f:
print(twocaracter, file=f)
with open('liczba1.txt', "r") as file:
z = file.read(1)
with open('liczba22.txt', "r") as fil:
b = fil.read(1)
print(int(z) + int(b))
you should do a type cast:
total = int(z) + int(b)
print(total)

delete empty quotes and pattern before it in python

I have a file as below, whenever there is a key with empty value, I want to delete the key and the empty quotes
My file
<items="20" product="abc" condition="new">
<items="10" product="" condition="new">
<items="50" product="xyz" condition="">
<items="" product="mno" condition="fair">
desired output
<items="20" product="abc" condition="new">
<items="10" condition="new">
<items="50" product="xyz">
<product="mno" condition="fair">
I tried somehting like this, this deleted only the quotes. I want to delete the quotes and the value before "="
f= open('test.txt','r')
A1=f.read()
for i in A1:
if i=="''":
A1.remove(i)
print A1
break
You could use a regular expression:
import re
with open('test.txt','r') as A1:
for i in A1:
print(re.sub('[a-z-]+=\"\" *', '', i))
A possible solution could be:
with open('test.txt','r+') as f:
for line in f:
Line=line[1:len(line)-1]
L=Line.split()
for k in L:
if("" not in k):
f.write(k)
f.write(" ")
You could write a function to pass the lines through:
with open('in_file', 'r') as f:
lines = f.readlines()
def process_line(line):
line = line.split('<')[1].rsplit('>')[0]
valids = [val for val in line.split(' ') if '""' not in val]
line = '<{}>\n'.format(' '.join(valids))
return line
with open('out_file', 'w') as f:
for line in lines:
f.write(process_line(line))
You can use regex,
with open('tmp.txt', 'r') as f_in:
with open('tmp_clean.txt', 'w') as f_outfile:
f_out = csv.writer(f_outfile)
for line in f_in:
line = line.strip()
row = []
if bool(re.search('(.*="")', line)):
line = re.sub('[a-z]+=\"\"', '',line)
row.append(line)
else:
row.append(line)
f_out.writerow(row)

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()

Can't properly remove line from text file

I have a text file called test.txt, with the following content:
This is a test
I want this line removed
I'm trying to write an algorithm in Python 2 that removes the second line ("I want this line removed") as well as the line break on the first line. I'm trying to output this to a second file called test_2.txt; however, the resulting test_2.txt file is empty, and the first line is not there. Why? Here is my code:
#coding: iso-8859-1
Fil = open("test.txt", "wb")
Fil.write("This is a test" + "\n" + "I want this line removed")
Fil.close()
Fil = open("test.txt", "rb")
Fil_2 = open("test_2.txt", "wb")
number_of_lines = 0
for line in Fil:
if line.find("I want") != 0:
number_of_lines += 1
line_number = 1
for line in Fil:
if line.find("I want") != 0:
if line_number == number_of_lines:
for g in range(0, len(line)):
if g == 0:
a = line[0]
elif g < len(line) - 1:
a += line[g]
Fil_2.write(a)
else:
Fil_2.write(line)
line_number += 1
Fil.close()
Fil_2.close()
You are overly complicating your algorithm. Try this instead:
with open('test.txt') as infile, open('test_2.txt', 'w') as outfile:
for line in infile:
if not line.startswith("I want"):
outfile.write(line.strip())
Remembering that open returns an iterator you can simplify, as well as generalise the solution, by writing it like this.
with open('test.txt') as infile:
first_line = next(infile)
with open('test_2.txt', 'w') as outfile:
outfile.write(first_line.strip())
# both files will be automatically closed at this point

Categories