Search code examples
pythonpython-3.xstringnonetype

Lines of txt read as NoneType


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

Solution

  • 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))