如何在Python中读取输入文件?

时间:2013-04-15 02:51:12

标签: python list

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

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

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来保存他们的输入数据。

我试过了:

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

但我觉得这不是解析任何给定输入文件的最佳方法。

解析输入文件的最佳做法是什么?我可以遵循的任何特定教程或指导?

3 个答案:

答案 0 :(得分:7)

不知道你的案例是整数还是字符串,所以我将它们解析为字符串:

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

修改

如果您对list comprehensions感到满意,请尝试:

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

答案 1 :(得分:2)

使用固定分隔符(如空格),您还可以使用:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import csv

with open("input.txt") as file: 
    reader = csv.reader(file, delimiter=' ')
    for row in reader:
        print row

答案 2 :(得分:0)

虽然在Python中你总会发现各种巧妙的技巧和节省时间(实际上,实际推荐用于真实项目的一次节省时间是with声明),我建议你直到对文件I / O非常熟悉,您应该坚持以下内容:

infile = open("input.txt", "r") # the "r" is not mandatory, but it tells Python you're going to be reading from the file and not writing

numCases = int(infile.readline())
infile.readline() #you had that blank line that doesn't seem to do anything
for caseNum in range(numCases):
    # I'm not sure what the lines in the file mean, but assuming each line is a separate case and is a bunch of space-separated strings:
    data = infile.readline().split(" ")
    # You can also use data = list(map(int, infile.readline.split(" "))) if you're reading a bunch of ints, or replace int with float for a sequence of floats, etc.
    # do your fancy algorithm or calculations on this line in the rest of this for loop's body

infile.close() # in the case of just reading a file, not mandatory but frees memory and is good practice

还可以选择这样做(如果您没有阅读大量数据,那么这取决于您自己的偏好):

infile = open("input.txt", "r")
lines = infile.read().strip().split("\n") # the .strip() eliminates blank lines at beginning or end of file, but watch out if a line is supposed to begin or end with whitespace like a tab or space
# There was the (now-redundant) line telling you how many cases there were, and the blank following it
lines = lines[2:]
for line in lines:
    # do your stuff here
infile.close()