Python open file statement reads a string from an empty file

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

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

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

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

+4
source share
4 answers

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 [''], not [].

+3
source

, :

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

.

+2

, split: :

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

and this is a list of one item, which is an empty string.

0
source

Reading an empty file returns ""and then splitting this empty line returns a [""]length of 1.

Try this instead:

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

Source: https://habr.com/ru/post/1628676/


All Articles