繁体   English   中英

txt 行读取为 NoneType

[英]Lines of txt read as NoneType

我正在使用 python3 在当前目录中打开一个文本文件并阅读所有行。

test.txt中的每一行都是图像的路径。

我的目标是获取文件扩展名之前的路径(有效),但是当我尝试使用path object 与不同的字符串连接时,python 无法将path识别为字符串str() 相反,它将其视为 NoneType。 我在这里做错了什么,解决方法是什么?

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

这是文件中的内容:

$ 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

print()函数返回None 您需要为分割结果分配path ,然后打印该path

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

但是,您应该将标准库用于此任务(版本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))

如果文件名大于1,则当前解决方案将无法提取扩展名之前的文件名部分. 在其中,这是很常见的。 使用pathlib可以避免此问题,并提供许多其他有用的功能。

在行中

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

您可以分配print的返回结果( None )。

您可能要使用:

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

并且不需要lines = ins.readlines()行。

总而言之,我建议您使用

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM