Reputation: 818
I am trying to write two things from two different files on the same line of a different file(That is there are 3 files being used. 2 that already have items and a new one )
fin=open("/Users/battledrum/Desktop/review2.txt")
fin1=open("/Users/battledrum/Desktop/review3.txt")
fout=open("/Users/battledrum/Desktop/HeightVStime.txt","w")
a=list()
for i in range(35):
fout.write(fin.read()+'\t'+fin1.read())
print(len(a))
this is the result i want to see in the new file:
1.34, 1.54
1.80, 1.39
1.25 , 1.68
1.69 , 1.83
Upvotes: 0
Views: 370
Reputation: 56634
Many things wrong with this:
file.read()
gets the entire contents of a file, so you are writing (the entire first file) + tab + (the entire second file) where you want to read line by line.
you never append to a
, so len(a)
will always be 0.
It isn't exactly clear what you want in a
- the line-by-line file contents?
I think you want something more like
HEIGHT_FILE = "/Users/battledrum/Desktop/review2.txt"
TIME_FILE = "/Users/battledrum/Desktop/review3.txt"
OUTPUT_FILE = "/Users/battledrum/Desktop/HeightVStime.txt"
def main():
# load data pairs
with open(HEIGHT_FILE) as hf, open(TIME_FILE) as tf:
hts = [(height.strip(), time.strip()) for height,time in zip(hf, tf)]
# write output
with open(OUTPUT_FILE, "w") as outf:
lines = ("{}\t{}".format(h, t) for h,t in hts)
outf.write("\n".join(lines))
print("{} lines written".format(len(hts)))
if __name__=="__main__":
main()
Upvotes: 1
Reputation: 1607
assuming the files are the same length
with open(fin) as f1:
with open(fin1) as f2:
num1 = [l.strip() for l in f1.readlines()]
num2 = [l.strip() for l in f2.readlines()]
with open(fout,'w+') as out:
for i in range(0,len(num1)):
out.write(','.join([num1[i], num2[i]])+'\n')
Upvotes: 0
Reputation: 5518
Rather than assuming a certain number of lines in each file, how about something like:
with open("/Users/battledrum/Desktop/HeightVStime.txt","w") as fout:
with open("/Users/battledrum/Desktop/review2.txt") as fin1:
with open("/Users/battledrum/Desktop/review3.txt") as fin2:
fout.writelines([(', '.join((x.rstrip('\n'),y))) for x,y in zip(fin1,fin2)])
zip
will combine lines between fin1
and fin2
, since we can treat each file object as an iterable and will throw away the remaining lines if one of the files is longer than the other.
Upvotes: 0