繁体   English   中英

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

[英]How to read input file in Python?

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

我最近开始学习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()

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

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

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

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

编辑

如果列表推导对您来说很舒服,请尝试:

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

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

#!/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

虽然在Python中你总会发现各种巧妙的技巧和节省时间(实际上,实际推荐用于实际项目的一个节省时间是with语句),我建议你直到你对File I /哦,你应该坚持下面这样的事情:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM