[英]expected str, bytes or os.PathLike object, not list ( want to get file names from list)
I'm trying to get only the file name without extension, what I still get this error even though it's what it says in the book I'm trying to read.我试图只获取不带扩展名的文件名,尽管这是我正在尝试阅读的书中所说的内容,但我仍然会收到此错误。
import os
import re
stringA =[fname.rsplit(' ',0)[0] for fname in os.listdir("C:\\Users\\Desktop\\New folder\\New folder\\")]
stringA1 = os.path.splitext(os.path.basename(stringA))[0]
I get this error:我收到此错误:
~\Anaconda3\lib\ntpath.py in basename(p)
214 def basename(p):
215 """Returns the final component of a pathname"""
--> 216 return split(p)[1]
217
218
~\Anaconda3\lib\ntpath.py in split(p)
183 Return tuple (head, tail) where tail is everything after the final slash.
184 Either part may be empty."""
--> 185 p = os.fspath(p)
186 seps = _get_bothseps(p)
187 d, p = splitdrive(p)
TypeError: expected str, bytes or os.PathLike object, not list
In the first line of your code - you want to split by a .
在你的代码的第一行 - 你想用.
and not by spaces as a .
而不是按空格作为.
would be the separator between a filename and its extension.将是文件名及其扩展名之间的分隔符。
Also, you want to pass a value of 1
to the maxsplit
argument - meaning that you want at most 1 split.此外,您希望将值1
传递给maxsplit
参数 - 这意味着您最多需要 1 次拆分。 0 means you don't want to split the input at all 0 表示您根本不想拆分输入
stringA =[fname.rsplit('.',1)[0] for fname in os.listdir("C:\\Users\\Desktop\\New folder\\New folder\\")]
To get all the the files in a folder only:-仅获取文件夹中的所有文件:-
import os
folder = "C:\\Users\\Folder"
for files in os.listdir(folder):
filelist = (files.partition(".")[0])
print(filelist)
To get all the files in folder and subfolders, use this:-要获取文件夹和子文件夹中的所有文件,请使用:-
import os
folder = "C:\\Users\\Folder"
for root, dir, files in os.walk(folder):
for file in files:
filelist = (file.partition(".")[0])
print(filelist)
If you want to obtain only the filename, without its extension and without the preceding path, you can combine the use of the os.path.splitext
function with the split
function from the string type:如果只想获取文件名,没有扩展名,也没有前面的路径,可以将os.path.splitext
function 与字符串类型的split
function 结合使用:
>>> import os
>>> p = 'c/folder/folder/file.txt'
>>> os.path.splitext(p)[0].split('/')[-1]
'file'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.