Lines of txt read as NoneType

Question:

I am using python3 to open a text file in the current directory and read through all of the lines.

Each line in test.txt is a path to an image.

My objective is to get the path before the file extension (which works), but then when I try to use the path object to concatenate with a different string, python doesn’t recognize path as a string object even after I try converting with str(). Rather, it sees it as NoneType. What am I doing wrong here and what is the workaround?

with open("test.txt", "r") as ins:
    lines = ins.readlines()
    for line in lines:
        path = print(line.split('.')[0])
        print(type(path))

Output:

/Users/admin/myfolder/IMG_1889
<class 'NoneType'>

with open("test.txt", "r") as ins:
    lines = ins.readlines()
    for line in lines:
        path = print(line.split('.')[0])
        print(str(path))

Output:

/Users/admin/myfolder/IMG_1889
None

this is what’s in the file:

$ cat test.txt
/Users/admin/myfolder/IMG_1901.jpg
/Users/admin/myfolder/IMG_1928.jpg
/Users/admin/myfolder/IMG_2831.jpg
/Users/admin/myfolder/IMG_1889.jpg
/Users/admin/myfolder/IMG_2749.jpg
/Users/admin/myfolder/IMG_1877.jpg
Asked By: the_darkside

||

Answers:

The print() function returns None. You need to assign path to the result of the split, then print that.

with open("test.txt", "r") as ins:
    lines = ins.readlines()
    for line in lines:
        path = line.split('.')[0]
        print(path)
        print(type(path))

You should, however, be using the standard library for this task (version 3.4+):

import pathlib

with open('test.txt', 'r') as ins:
    for path in (pathlib.Path(line) for line in ins):
        print(path.stem)
        print(type(path.stem))

Your current solution would fail to extract the part of the filename before the extension if the filename has more than 1 . in it, which is fairly common. Using pathlib avoids this issue, and provides many more useful features.

Answered By: Will Da Silva

in the line

path = print(line.split('.')[0])

you assign the return result of print (which is None).

you might want to use:

path = line.split('.')[0]
print(path)

and there is no need for the lines = ins.readlines() line.

all in all i suggest you use

with open("test.txt", "r") as ins:
    for line in ins:
        path = line.split('.')[0]
        print(path)
        print(type(path))
Answered By: hiro protagonist

with open("test.txt", "r") as ins:
for line in ins:
if line is not None:
path = line.split(‘.’)[0]
print(type(path))

Answered By: Abhishek
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.