Gagandeep
Gagandeep

Reputation: 39

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

Upvotes: 2

Views: 12360

Answers (3)

CodeWithYash
CodeWithYash

Reputation: 251

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)

Upvotes: 1

Atalajaka
Atalajaka

Reputation: 125

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:

>>> import os
>>> p = 'c/folder/folder/file.txt'
>>> os.path.splitext(p)[0].split('/')[-1]
'file'

Upvotes: 0

Mortz
Mortz

Reputation: 4879

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. 0 means you don't want to split the input at all

stringA =[fname.rsplit('.',1)[0] for fname in os.listdir("C:\\Users\\Desktop\\New folder\\New folder\\")]

Upvotes: 1

Related Questions