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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16006974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:34:55  来源:igfitidea点击:

How to read input file in Python?

pythonlist

提问by CracLock

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

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

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

现在要开始解决问题,您需要控制输入数据。我已经看到在 python 开发人员主要用于Lists保存他们的输入数据。

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?

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

采纳答案by waitingkuo

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

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

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 comprehensionsis comfortable to you, try:

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

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

回答by SimonT

Although in Python you'll invariably discover all sorts of neat tricks and time-savers (in fact, one time-saver that is actually recommended for real projects is the withstatement), I recommend that until you are really comfortable with File I/O, you should stick to something like the following:

尽管在 Python 中您总会发现各种巧妙的技巧和节省时间的方法(实际上,实际上推荐用于实际项目的一种节省时间的方法是with语句),但我建议您在真正熟悉 File 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

There is also the option of doing it like this (really up to your own preference if you're not reading a lot of data):

也可以选择这样做(如果您没有阅读大量数据,这完全取决于您自己的喜好):

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

回答by Nykakin

With fixed delimiter like space you can also use:

使用像空格这样的固定分隔符,您还可以使用:

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