Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read input file in Python?

Tags:

python

list

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?

like image 700
CracLock Avatar asked Apr 15 '13 02:04

CracLock


People also ask

What is input file in Python?

input() method, we can get the file as input and to can be used to update and append the data in the file by using fileinput. input() method. Syntax : fileinput.input(files) Return : Return the data of the file.

How do I open an input file?

If you cannot open your INPUT file correctly, try to right-click or long-press the file. Then click "Open with" and choose an application. You can also display a INPUT file directly in the browser: Just drag the file onto this browser window and drop it.


3 Answers

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)]
like image 112
waitingkuo Avatar answered Oct 26 '22 19:10

waitingkuo


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
like image 40
Nykakin Avatar answered Oct 26 '22 19:10

Nykakin


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 with statement), I recommend that until you are really comfortable with File I/O, you should stick to something like the following:

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()
like image 35
SimonT Avatar answered Oct 26 '22 20:10

SimonT