1

This is what I'm doing. I'm taking a text from a folder, modifying that text, and writing it out to another folder with a modified file name. I'm trying to establish the file name as a variable. Unfortunately this happens:

import os
import glob
path = r'C://Users/Alexander/Desktop/test/*.txt'
for file in glob.glob(path):
    name = file.split(r'/')[5]
    name2 = name.split(".")[0]
    print(name2)

Output: test\indillama_Luisa_testfile

The file name is 'indillama_Luisa_testfile.txt' it is saved in a folder on my desktop called 'test'.

Python is including the 'test\' in the file name. If I try to split name at [6] it says that index is out of range. I'm using regex and I'm assuming that it's reading '/*' as a single unit and not as a slash in the file directory.

How do I get the file name?

Wangana
  • 71
  • 1
  • 9

3 Answers3

1
import os
import glob
path = r'C://Users/Alexander/Desktop/test/*.txt'
for file in glob.glob(path):
    name = os.path.basename(file)
    (path, ext) = os.path.splitext(file)
    print(ext)

os.path.basename() will extract the filename part of the path. os.path.splitext() hands back a tuple containing the path and the split-off extension. Since that's what your example seemed to be printing, that's what I did in my suggested answer.

For portability, it's usually safer to use the built-in path manipulation routines rather than trying to do it yourself.

Will
  • 24,082
  • 14
  • 97
  • 108
Tom Barron
  • 1,554
  • 18
  • 23
1

You can split by the OS path separator:

import os
import glob

path = r'C://Users/Alexander/Desktop/test/*.txt'
for file in glob.glob(path):
    name = file.split(os.path.sep)[-1]
    name2 = name.split(".")[0]
    print(name2)
Natsukane
  • 681
  • 1
  • 8
  • 19
  • This worked, thanks! But I'm not sure how it works. How does os.path.sep split the string? And why the -1 for the list position? – Wangana Jun 08 '16 at 21:33
  • @AlexR. os.path.sep is the string the current OS uses for separating file paths. The [-1] just means "the last element in the list", which in this case is the filename. – Natsukane Jun 08 '16 at 21:51
0

You can use os.listdir(path) to list all the files in a directory. Then iterate over the list to get the filename of each file.

for file in os.listdir(path):
    name2 = file .split(".")[0]
    print(name2)
schafle
  • 615
  • 4
  • 10