python中怎么读取文件_如何在Python中读取输入文件?

1586010002-jmsa.png

Please excuse me if I'm asking a stupid question but I believe I have an issue.

I recently started learning Python and I tried solving some Algorithm based problems. But one issue is that every Algo challenge comes with some Input file. It usually consists of some test case count, test cases etc. like

4 #cases

1 2 5 8 4 #case 1

sadjkljk kjsd #case 2

5845 45 55 4 # case 3

sad sdkje dsk # case 4

Now to start solving problem you need control on you input data. I have seen that In python developers mostly use Lists to save their input data.

I tried:

fp = open('input.txt')

for i, line in enumerate(fp.readlines()):

if i == 0:

countcase = int(i)

board.append([])

else:

if len(line[:-1]) == 0:

currentBoard += 1

board.append([])

else:

board[currentBoard].append(line[:-1])

fp.close()

But I don't feel like that's best way to parse any given input file.

What are best practices to parse the input file? Any specific tutorial or guidance I could follow?

解决方案

Don't know whether your cases are integers or strings, so I parse them as strings:

In [1]: f = open('test.txt')

In [2]: T = int(f.readline().strip())

In [3]: f.readline()

Out[3]: '\n'

In [4]: boards = []

In [5]: for i in range(T):

...: boards.append(f.readline().strip().split(' '))

...:

In [7]: for board in boards: print board

['1', '2', '5', '8', '4']

['sadjkljk', 'kjsd']

['5845', '45', '55', '4']

['sad', 'sdkje', 'dsk']

EDIT

If list comprehensions is comfortable to you, try:

boards = [f.readline().strip().split(' ') for i in range(T)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值