appending files in python - python

I have a homework assignment working with fixed length files:
You will be passed the filename P, firstname F, lastname L, and a new birthday B.
Load the fixed length record file in P, search for F,L in the first and change birthday to B.
P= sys.argv[1]
F= sys.argv[2]
L= sys.argv[3]
B= sys.argv[4]
recordlength = 40
record = [[]]
start = 0
file1 = open(P, 'r')
data = file1.read()
while( (len(data) - start) >= recordlength):
records= data[start:start + recordlength]
record.append(records)
start+= recordlength
for i in range(0,len(record)):
if F and L in record[i]:
rec = record[i]
rec = rec[:-8] + B
record[i] = rec
data = "".join(records)
file1 = open(P, 'a+')
file1.write(record[i])
file1.close()
I should get this output:
Adam Smith 11111985Theodore Anderson 03201990Monty Biscuit-Barrel 10181980Adam Smithers 00000000Ruthy Anderson 06062010
I get this output:
Adam Smith 11111985Theodore Anderson 03201990Monty Biscuit-Barrel 10181980Adam Smithers 10101960Ruthy Anderson 06062010Adam Smithers 00000000
Instead of replacing this line: Adam Smithers 10101960, with this line: Adam Smithers 00000000, it adds this line into the file, leaving the original line.
I'm not sure where my problem is, can someone point me in the right direction?

On line 8 you open the file but do not close before opening again on line 20. Try to close before line 20 or open with parameter "a" directly on line 8.

Related

Assistance working with Files in Python 3

I am currently taking an introduction class to python scripting and am in need of help. The below variables are given
The file name -> P = test.txt
firstname -> F = 'Ruthy'
lastname -> L = 'Anderson'
new birthday-> B = 00000000
The objective is to search the file for the given first and last name and then replace the current birthday that is there with the 'B' variable. We are told that each record has a fixed length of 40.
Below is what the test.txt file contains
Adam Smith 11111985Theodore Anderson 03201990Monty Biscuit-Barrel 10181980Adam Smithers 11111900Ruthy Anderson 06062010
This is the code that I have thus far.
file1 = open(P, 'r')
data = file1.read()
file1.close()
file2 = open(P, 'w')
recordLength = 40
start = 0
records = []
while((len(data) - start) >= recordLength):
record = data[start:start + recordLength]
records.append(record)
start+= recordLength
for i in range(0, len(records)):
if re.seatch(F, data) and re.search(L, data):
data = re.sub('10101960', B, data)
file2.write(data)
file2.close()
IIUC my approach would be the following:
# P = 'test.txt'
# F = 'Ruthy'
# L = 'Anderson'
# B = '00000000'
with open(P, 'r+') as f:
while True:
rec = f.read(40)
if rec:
if rec.startswith(f'{F} {L}'):
pos = f.tell()
f.seek(pos-8)
f.write(B)
break
else:
break

Python 3 How do I append a list in a file?

This is the data my file:
John Smith, 5
Luke Smith, 7
Mary Smith, 8
Boby Smith, 2
I want to be able to add another number onto a specific user in the file. See below (Mary).
John Smith, 5
Luke Smith, 7
Mary Smith, 8, 6
Boby Smith, 2
My code:
with open('filename.txt','a') as file:
file.write("\n{}, {}".format(name,number))
This code will append/write to the file just fine, but it writes in new users each time, which I do not want it to do. I want it to check to see if a user is already in the file, and append that line with the new number. If user does not already exist, add them to the file.
Try this
value = 5
user = input('Please enter a username: ')
with open('myfile.txt', 'r+') as f:
var = f.readlines()
if user in ''.join(var):
for count, line in enumerate(var):
if user in line:
found = line.strip() + ', ' + str(value) + '\n'
var[count] = found
else:
'{} not in the file but has been added'
var.append(user + ' ' + str(value) + '\n')
with open('myfile.txt', 'w') as f:
f.writelines(var)
There should be a better way than opening the file twice, but it works
This will work:
file = open('filename.txt','r')
file.read()
data = file.replace('Mary Smith, 8', 'Mary Smith, 8, 6')
file.close()
file = open('filename.txt', 'w')
file.write(data)
file.close()

Python: How do i sort Names in a text file alphabetically?

my questions is, how to i sort by the 1st letter of the person's name in a text file(A at the top going to Z at the bottom). I use python 3.4.3.
I have a text file containing names and scores: = ('test', ' ', 1)
I've tried the code below however it doesn't seem to sort alphabetically.
age = class number
file = open(str(age) + ".txt" , "a")
file.write(name + " " + " {}\n".format(score))
f = open(str(age) + ".txt" , "r")
lines = f.readlines()
f.close()
lines.sort()
f = open(str(age) + ".txt" , "w")
for line in lines:
f.write(line)
f.flush()
f.close()
print(lines)
The problem is probably in your file. The code you posted works fine for a .txt file such as:
Dave = 12
Peter = 5
Agnes = 4
Charles = 10
Mary = 8
Please post your file.

My function takes a string as an argument and prints in a different format. I want to open a file and call my function on the lines in the file

The function for example currently works and would change the following:
13126 Physics 25000 Sarah Jane Smith
to:
Smith,Sarah Jane 13126 Physics 25000
I am trying to make this function do the same to the lines of text in an external file. The lines in the external file take the format:
12345 CSEE 35000 Bart Simpson
12346 CSEE 25000 Harry Potter
12350 Economics 30000 Krusty The Clown
13123 Economics 55000 David Cameron
13124 Lingustics 40000 Louis VanGaal
13126 Physics 25000 Sarah Jane Smith
13127 History 35000 Tony Blair
I am trying to call my function to format these lines the same way as the example above. My code currently prints an output but its totally incorrect.
This is my code:
print""
# To God be the Glory
Payroll = []
Department = []
Salary = []
name1 = []
name2 = []
possiblename3 = []
print ""
String = raw_input("Please enter the lecturers details: ")
def printFormat(String):
String = String.split()
Payroll.append(String[0])
Department.append(String[1])
Salary.append(String[2])
name1.append(String[3])
name2.append(String[4])
if len(String) == 6:
possiblename3.append(String[5])
print""
if possiblename3 != "":
print "%s,%s %s %s %s %s" % (','.join(possiblename3),', '.join(name1),', '.join(name2),', '.join(Payroll),', '.join(Department),', '.join(Salary))
else:
print "%s %s %s %s %s" % (', '.join(name1),', '.join(name2),', '.join(Payroll),', '.join(Department),', '.join(Salary))
print printFormat(String)
print ""
fname = input("Enter filename: ")
try :
f = open(fname)
myLine = f.readline()
while (len(myLine)>0) :
# print generates a newline so we do not want
# the newline from the string
print printFormat(myLine)
myLine = f.readline()
print ""
#f.close()
except IOError as e :
print("Problem opening file")
If you only either have 5 or 6 words depending on whether there is a middle name or not, get the last element from the split string as the last name, use from element 3 i.e the first name slicing to the second last so you will either get a single word or both words if the user has a middle name:
with open("in.txt") as f:
for line in f:
data = line.split()
print("{},{} {}".format(data[-1]," ".join(data[3:-1])," ".join(data[:3])))
Using your input lines, outputs:
Simpson,Bart 12345 CSEE 35000
Potter,Harry 12346 CSEE 25000
Clown,Krusty The 12350 Economics 30000
Cameron,David 13123 Economics 55000
VanGaal,Louis 13124 Lingustics 40000
Smith,Sarah Jane 13126 Physics 25000
Blair,Tony 13127 History 35000
You can also use the csv module to read in and split the data:
import csv
with open("in.txt") as f:
r = csv.reader(f,delimiter=" ")
for row in r:
print("{},{} {}".format(row[-1]," ".join(row[3:-1])," ".join(row[:3])))
And also use it to write the reformatted data to the original file using a NamedTemporaryFile and shutil.move:
import csv
from tempfile import NamedTemporaryFile
from shutil import move
with open("in.txt") as f, NamedTemporaryFile(delete=False,dir=".") as out:
wr = csv.writer(out)
r = csv.reader(f,delimiter=" ")
for row in r:
wr.writerow(['{},{}'.format(row[-1], " ".join(row[3:-1]))," ".join(row[:3])])
in.txt after will look like:
"Simpson,Bart",12345 CSEE 35000
"Potter,Harry",12346 CSEE 25000
"Clown,Krusty The",12350 Economics 30000
"Cameron,David",13123 Economics 55000
"VanGaal,Louis",13124 Lingustics 40000
"Smith,Sarah Jane",13126 Physics 25000
"Blair,Tony",13127 History 35000
Try this for your function:
def printFormat(String):
String = String.split()
lastname = String[-1]
firstnames = " ".join(String[3:-1])
name = ", ".join([lastname, firstnames])
otherstuff = " ".join(String[:3])
return " ".join([name, otherstuff])

Python: Formatting a merged txt file

I want to merge two text files: names.txt and studentid.txt
the name txt contains:
Timmy Wong, Johnny Willis, Jason Prince
the studentid.txt contains:
B5216, B5217, B5218
I want to combine them into a new text file called studentlist.txt with the format I simply want all the commas to become vertical bars
Student_Name Student_ID
Timmy Wong | B5216
Johnny Willis | B5217
Jason Prince | B5218
So far I don't really know how to format this been reading up some guides and my book but it really isn't helping much.
This is what I done so far
def main():
one = open( "names.txt", 'r' )
lines = one.readlines()
two = open( "studentid.txt", 'r' )
lines2 = two.readlines()
outfile = open( "studentlist.txt", 'w' )
outfile.write( "Student_Name StudentID")
outfile.writelines( lines + lines2 )
main()
and the output becomes
Student_Name StudentIDTimmy Wong, Johnny Willis, Jason Prince
B5216, B5217, B218
I'm a beginner so go easy on me ><"
names = [n.strip() for n in open("names.txt").read().split(",")]
ids = [i.strip() for i in open("studentid.txt").read().split(",")]
print "Student_Name\t| Student_ID"
for n, i in zip(names, ids):
print "{}\t| {}".format(n, i)
with open('data.txt') as f1,open('data1.txt') as f2,open('sudentlist.txt') as f3:
line=f1.readline().strip() #read the first line of names file
names=map(str.strip,line.split(',')) #split the line by "," and then apply strip()
line=f2.readline().strip() #read the first line of ID file
ids=map(str.strip,line.split(',')) #split the line by "," and then apply strip()
f3.write("{0:25}{1}\m".format("Student_Name","Student_Id"))
for name,i in zip(names,ids): #use zip() to fetch data from both lists
f3.write("{0:25}|{1}\n".format(name,i)) #use write() instead of print to write it to a file
output:
Student_Name Student_Id
Timmy Wong |B5216
Johnny Willis |B5217
Jason Prince |B5218
Untested, but you want something similar to:
import csv
with open('names.txt') as nf, open('studentid.txt') as sf, open('output.txt','wb') as pf:
csvnf = csv.reader(nf)
csvsf = csv.reader(sf)
csvpf = csv.writer(pf, delimiter='|')
for name_student in zip(csvnf, csvsf):
pf.writerow( name_student )
names = [n.strip() for n in open("names.txt").read().split(",")]
student_ids = [i.strip() for i in open("studentid.txt").read().split(",")]
outfile = open("studentlist.txt", 'w')
outfile.write("Student_Name\tStudent_ID\n")
for current_name, current_id in zip(names, student_ids):
outfile.write(current_name + "\t|" + current_id + "\n")
outfile.close()

Categories