Home > Post > Reading number from file in Python

Reading number from file in Python

December 10th, 2009 Fu4ny Leave a comment Go to comments

Err, that was  a long time since my last tutorial. I'm learning Python now, and I decided to write some tutorials for it.

As you know, there's a simple concept about Python: "You have plenty of way to do things". This is, sometime, a advantages, but sometimes it's hard to decide the way you do "your things".

Today, I'll show you some ways to read number from file input, The good, the bad, and the ugly

The good, tradition, easy:

1
2
3
4
5
6
fin = open("input.txt","r")
for line in fin.readlines():
   #unpack with line.split()
   p = line.split()
   #Get your variable
   n = int(p[0])

Why it's good: it's easy to understand, easy to maintain, easy to write (but slow as hell ).

It's just do the job: read line one by one, split and pack number in to a tuple

The bad, tradition, and still works

1
2
3
4
5
fin = open("input.txt","r")
t = fin.read()
inputTuple = t.split()
for i in inputTuple:
    print i

Thingy: it's just read all the file, split and store all the number into a tuple, whenever you want them or not. It's just eating you RAM, *yum yum*

The ugly, if you want one-liner

1
[i for x in [x.split() for x in open('input.txt')] for i in x]

It's just very good, do all the thing in "The bad" ways, but with only one-line. Do it if you don't want anyone to understand your code.

The IDK, if you just want to read 1 number

1
2
3
4
fin = open("input.txt",'r')
n = ''
while ( n[-1] != ' ' ): n += fin.read(1)
n = int(n[:-1])

Another, just works, easy to understand code.

Is there any other ways that you know ;)

Categories: Post Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.