Error trying to add lines to txt - python

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

Related

How do I match two plain text files line by line using Python

As per my requirement, I wish to match two text files line by line in Python on Windows platform. for example I have the following text files:
File1:
My name is xxx
command completed successfully.
My mother's name is yyy
My mobile number is 12345
the heavy lorry crashed into the building at midnight
lorry eat in the faculty a red apple
File2:
My name is xxx
command . successfully.
The name of my mother is
what a heavy lorry it is that crashed into the building
lorry eat an apple in the faculty
I apologize for not being clear enough so my problem is how can i align a script movie with its subtitles, i writ the following code in Python but it's not enough to get the alignement from the two text files:
# Open file for reading in text mode (default mode)
f1 = open('F:/CONTRIBUTION 2017/SCRIPT-SUBTITLES CODES/Script Alignement Papers/f1.txt','r')
f2 = open('F:/CONTRIBUTION 2017/SCRIPT-SUBTITLES CODES/Script Alignement Papers/f2.txt','r')
#Print confirmation
# print("-----------------------------------")
#print("Comparing files ", " > " + fname1, " < " +fname2, sep='\n')
# print("-----------------------------------")
# Read the first line from the files
f1_line = f1.readline()
f2_line = f2.readline()
# Initialize counter for line number
line_no = 1
# Loop if either file1 or file2 has not reached EOF
while f1_line != '' or f2_line != '':
# Strip the leading whitespaces
f1_line = f1_line.rstrip()
f2_line = f2_line.rstrip()
# Compare the lines from both file
if f1_line != f2_line:
# If a line does not exist on file2 then mark the output with + sign
if f2_line == '' and f1_line != '':
print("=================================================================")
print("=================================================================")
print("line does not exist on File 2 ====================")
print("=================================================================")
print(">+", "Line-%d" % line_no, f1_line)
# otherwise output the line on file1 and mark it with > sign
elif f1_line != '':
print("=================================================================")
print("=================================================================")
print("otherwise output the line on file1 ====================")
print("=================================================================")
print(">", "Line-%d" % line_no, f1_line)
# If a line does not exist on file1 then mark the output with + sign
if f1_line == '' and f2_line != '':
print("=================================================================")
print("=================================================================")
print("=line does not exist on File 1 ====================")
print("=================================================================")
print("<+", "Line-%d" % line_no, f2_line)
# otherwise output the line on file2 and mark it with < sign
elif f2_line != '':
print("=================================================================")
print("=================================================================")
print("otherwise output the line on file2 ====================")
print("=================================================================")
print("<", "Line-%d" % line_no, f2_line)
# Print a blank line
print()
#Read the next line from the file
f1_line = f1.readline()
f2_line = f2.readline()
#Increment line counter
line_no += 1
# Close the files
f1.close()
f2.close()
If can anyone help to do this matching, i would be very grateful.
It would be good to post code you tried writting. This feels like we are doing your homework and makes you look lazy. That being said, take a look at the following:
with open(file1, 'r') as f1, open(file2, 'r') as f2:
if f1.readlines() == f2.readlines():
print('Files {} & {} are identical!'.format(file1, file2))
PS: This checks whether the files are identical. If you want something like a logical comparison you have to do some research first.
One possible way is to store the lines of the file in a list and then compare the lists.
lines_of_file1 = []
file = open("file1.txt","r")
line = 'sample'
while line != '':
line = file.readline()
lines_of_file1.append(line)
file.close()
lines_of_file2 = []
file = open("file2.txt","r")
line = 'sample'
while line != '':
line = file.readline()
lines_of_file2.append(line)
file.close()
same = True
for line1 in lines_of_file1:
for line2 in lines_of_file2:
if line1 != line2:
same = False
break
if same:
print("Files are same")
else:
print("Files are not same")
Hope that helps.

Prepend line number to string in 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()

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

How to generate an index for a file?

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

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