4

I am trying to read a file using the following statement:

input = open("input.txt").read().split('\n')

So basically my objective is to read the file line by line and store results in an array. It works perfect when the file is not empty. When input file has only one line len(input) is 1, which is as expected.

But when the file is empty, len(input) still gives 1. What am I doing wrong?

2
  • Which version of python are you running? 2.x or 3.x? Commented Feb 14, 2016 at 1:03
  • @Nicarus i'm using 2.7.9 Commented Feb 14, 2016 at 1:04

4 Answers 4

3

You should use open("input.txt").readlines(), not open("input.txt").read().split("\n"). If you try "".split("\n") in the interpreter, you will see that the result is [''], not [].

Sign up to request clarification or add additional context in comments.

2 Comments

@ikis - you should mark this as the correct answer if it was your solution.
@Nicarus stack overflow didn't allow me to accept it within 10 mins. I have already attempted. Will do it as soon as it become available.
2

Iterating a file gives you the lines, so you could use:

the_input = list(open("input.txt"))

though this will include the newline characters in the strings.

1 Comment

(I used the dots because comments must be 15 characters, for whatever reason.)
0

Well, this is how split works: This is happening:

>>> ''.split(',')
['']

and it is a list of one element which is the empty string.

Comments

0

Reading the empty file returns "", and then splitting that empty string returns [""], which has length 1.

Try this instead:

lines = open("empty.txt").readlines()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.