使用for循环写入文件

问题描述 投票:0回答:1

我有一个for循环,该循环遍历Dataframe并打印一些行,也许是2或3。我编写了代码,但只将最后一行写到文本文件中。这是我的代码:

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)
python dataframe text-files
1个回答
0
投票

我没有足够的声誉来发表评论,但是我认为,如果您将模式从'w'更改为'a',它将在通过数据帧时追加。

您正在遍历数据框并每次写入,因此它将覆盖现有数据。

© www.soinside.com 2019 - 2024. All rights reserved.