0

I have a for loop which goes through a Dataframe and print some rows, maybe 2 or 3. I have written a code but it only write the last row to the text file. here is my code:

data = read_csv()
#how to change this line
data = data.set_index('Seat No')
print('Here is your ticket...')
x=read_file()
for seat_no in x:
    row=data.loc[int(seat_no)]
    ticket = open('ticket.txt', 'w')
    old_stdout = sys.stdout
    sys.stdout = ticket
    ticket.writelines('''
        {}-{} {}
         {}
        '''.format(row.Source, '%4s' % row.Destination, '%2s' % row.Departure, '%2s' % seat_no))
    sys.stdout = old_stdout
    ticket.close()
    printed_ticket = open('ticket.txt').read()
    print(printed_ticket)
Mahsa
  • 1
  • 2

2 Answers2

2

I don't have enough reputation to comment, but I think if you change mode from 'w' to 'a' it will append as it goes through the dataframe.

You're iterating over your dataframe and writing each time, so it will overwrite the existing data.

nos codemos
  • 569
  • 1
  • 5
  • 19
  • Thanks but I want to add new rows to the file and delete the each time I run the program. If I use append the information will be in the file. – Mahsa Dec 12 '19 at 12:26
  • https://stackoverflow.com/questions/4914277/how-to-empty-a-file-using-python you can try adding this line `open(file, 'w').close` which will render the file empty, and then open it again on the line below without the close, as you have done, in `'a'`. I'm not sure how efficient it will be on memory or anything, but worth a shot if you just need a means to an end. I'm not sure if I am misunderstanding you. – nos codemos Dec 12 '19 at 12:31
  • @noscodemos opening the same file over and over and over again in a loop - even if for appending - is a very bad idea anyway. Opening a file is a quite costly operation, so you want to do it only once if you can. IOW, the proper solution here is to open the file only once before the loop. – bruno desthuilliers Dec 12 '19 at 13:23
1

Calling open('ticket.txt', 'w') causes overwriting of the file, so use 'a' instead if you want to append.

Also, close should be automated by with open... like so:

with open('ticket.txt', 'a') as ticket:
    for seat_no in x:
        ticket.writelines('''...

The last two lines (when opening the file for reading again) look like you might want to move them outside of the loop.

V-R
  • 1,309
  • 16
  • 32
  • Thank you so much for your help it actually worked when i opened the file before for loop. – Mahsa Dec 12 '19 at 12:33