Python: Formatting a merged txt file - python

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

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

How to replace string character pattern using python in csv file

I am new to python. How to replace string character ," to ,{ and ", to }, which contains multilines in .csv file?
Here is my content of .csv file
Name, Degree,Some, Occupation, Object
Mr. A,"B.A, M.A",123,"ags,gshs",ass
Mr. ABC,"B.A, M.A",231,"ags,gshs",asas
Mr. D,"BB.A, M.A",44,"ags,gshs",asas
Mr. G,"BBBB.A, M.A",12,"ags,gshs",asasasa
Mr. S,"B.A, MMM.A",10,"ags,gshs",asasas
Mr. R,"B.A, M.A",11,"ags,gshs",asasas
Mr. T,"B.A, M.A",12,"ags,gshs",asasa
Mr. DD,"B.A, M.A",13,"ags,gshs",asasas
So my output will be something like this
Name, Degree,Some, Occupation, Obejct
Mr. A,{B.A, M.A},123,{ags,gshs},ass
Mr. ABC,{B.A, M.A},231,{ags,gshs},asas
Mr. D,{BB.A, M.A},44,{ags,gshs},asas
Mr. G,{BBBB.A, M.A},12,{ags,gshs},asasasa
Mr. S,{B.A, MMM.A},10,{ags,gshs},asasas
Mr. R,{B.A, M.A},11,{ags,gshs},asasas
Mr. T,{B.A, M.A},12,{ags,gshs},asasa
Mr. DD,{B.A, M.A},13,{ags,gshs},asasas
After opening the file with file.read(), you can use replace(old, new) to replace the string characters you desire. Keep in mind, since the strings ," and ", contain quotes, you must put a \ before the quotes to show they part of the string.
EDIT: A comment mentioned you could enclose the string in ' '. If you do this, putting \ before the quotes is not required. For example, both ",\"" and ',"' are valid strings.
data = ""
with open("/path/to/file.csv") as file:
data = file.read().replace(",\"", ",{").replace("\",", "},")
with open("/path/to/new_file.csv") as file:
file.write(data)
If you only need it once you could use pandas like this:
import pandas as pd
data1 = '''\
Name,Degree,Some,Occupation,Object
Mr. A,"B.A, M.A",123,"ags,gshs",ass
Mr. ABC,"B.A, M.A",231,"ags,gshs",asas
Mr. D,"BB.A, M.A",44,"ags,gshs",asas
Mr. G,"BBBB.A, M.A",12,"ags,gshs",asasasa
Mr. S,"B.A, MMM.A",10,"ags,gshs",asasas
Mr. R,"B.A, M.A",11,"ags,gshs",asasas
Mr. T,"B.A, M.A",12,"ags,gshs",asasa
Mr. DD,"B.A, M.A",13,"ags,gshs",asasas'''
df = pd.read_csv(pd.compat.StringIO(data1), sep=',', dtype=object)
#df = pd.read_csv('input.csv', sep=',', dtype=object) # Use this row for real application
df['Degree'] = '{'+df['Degree']+'}'
df['Occupation'] = '{'+df['Occupation']+'}'
# Create custom output
out = '\n'.join([','.join(df.columns), '\n'.join(','.join(i) for i in df.values)])
with open('output.csv') as f:
f.write(out)
You can use unpacking:
import csv
with open('filename.csv') as f:
data = filter(None, list(csv.reader(f)))
with open('filename.csv', 'w') as f1:
write = csv.writer(f1)
write.writerows([data[0]]+[[a, '{'+b+'}', c, '{'+d+'}', e] for a, b, c, d, e in data[1:]])
Output:
Name, Degree,Some, Occupation, Object
Mr. A,{B.A, M.A},123,{ags,gshs},ass
Mr. ABC,{B.A, M.A},231,{ags,gshs},asas
Mr. D,{BB.A, M.A},44,{ags,gshs},asas
Mr. G,{BBBB.A, M.A},12,{ags,gshs},asasasa
Mr. S,{B.A, MMM.A},10,{ags,gshs},asasas
Mr. R,{B.A, M.A},11,{ags,gshs},asasas
Mr. T,{B.A, M.A},12,{ags,gshs},asasa
Mr. DD,{B.A, M.A},13,{ags,gshs},asasas
Try:
def find_replace(csv_path, search_characters, replace_with):
text = open(csv_path, "r")
text = ''.join([i for i in text]).replace(
search_characters, replace_with)
x = open(csv_path, "w")
x.writelines(text)
x.close()
if __name__ == '__main__':
csv_path = "path/to/csv/file.csv"
search_characters = ',"'
replace_with = ',{'
find_replace(csv_path, search_characters, replace_with)
search_characters = '",'
replace_with = '},'
find_replace(csv_path, search_characters, replace_with)
The above code opens the file, writes some data to it and then closes it.
Or, if you prefer lists as well the with statement which will take care to call __exit__ function of the given object even if something bad happened in code.
def find_replace(csv_path, search_characters, replace_with):
s_one, s_two = search_characters
r_one, r_two = replace_with
with open(csv_path) as file:
data = file.read().replace(s_one, r_one).replace(s_two, r_two)
with open(csv_path, 'w') as file:
file.write(data)
if __name__ == '__main__':
csv_path = "path/to/csv/file.csv"
search_characters = [',"', '",']
replace_with = [',{', '},']
find_replace(csv_path, search_characters, replace_with)
The main advantage of using a with statement is that it makes sure our file is closed without paying attention to how the nested block exits.
Tested and works nicely on your example.
Replacing string character pattern using python in csv file
text = open("input.csv", "r")
#text = ''.join([i for i in text]).replace("character to be replaced", "character to be replaced with")
text = ''.join([i for i in text]).replace(",\"", ",{")
#Replacing character from replaced text
text1 = ''.join([i for i in text]).replace("\",", "},")
x = open("output.csv","w")
x.writelines(text1)
x.close()

appending files in 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.

Python: Add a new line after the first word in a sentence if the first word is all caps

I'm trying to modify a txt file. The file is a movie script in the format:
BEN We’ve discussed this before.
LUKE I can be a Jedi. I’m ready.
I'd like insert a new line after the character:
BEN
We’ve discussed this before.
LUKE
I can be a Jedi. I’m ready.
How do I do this in python? I currently have:
def modify_file(file_name):
fh=fileinput.input(file_name,inplace=True)
for line in fh:
split_line = line.split()
if(len(split_line)>0):
first_word = split_line[0]
replacement = first_word+'\n'
first_word=first_word.replace(first_word,replacement)
sys.stdout.write(first_word)
fh.close()
As suggested in one of the comments, this can be done using split and isupper. An example is provided below:
source_path = 'source_path.txt'
f = open(source_path)
lines = f.readlines()
f.close()
temp = ''
for line in lines:
words = line.split(' ')
if words[0].isupper():
temp += words[0] + '\n' + ' '.join(words[1:])
else:
temp += line
f = open(source_path, 'w')
f.write(temp)
f.close()
There are multiple problems with your code.
import fileinput
def modify_file(file_name):
fh=fileinput.input("output.txt",inplace=True)
for line in fh:
split_line = line.split()
if(len(split_line)>0):
x=split_line[0]+"\n"+" ".join(split_line[1:])+"\n"
sys.stdout.write(x)
fh.close() #==>this cannot be in the if loop.It has to be at the outer for level

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.

Categories