如何在Python中读取输入文件? [英] How to read input file in Python?

查看:152
本文介绍了如何在Python中读取输入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我问的是一个愚蠢的问题,请原谅,但我相信我有一个问题.

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

我最近开始学习Python,并尝试解决一些基于算法的问题.但是一个问题是,每个Algo挑战都带有一些输入文件.它通常由一些测试用例计数,测试用例等组成,例如

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

现在开始解决问题,您需要对输入数据进行控制.我已经看到在python中,开发人员大多使用Lists保存输入数据.

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.

我尝试过:

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

这篇关于如何在Python中读取输入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆