-3

So in my program, I am reading in files and processing them.

My output should say just the file name and then display some data

When I am looping through files and printing output by their name and data,

it displays for example: myfile.txt. I don't want the .txt part. just myfile.

how can I remove the .txt from the end of this string?

Alexandr Shurigin
  • 3,921
  • 1
  • 13
  • 25
TwinDream
  • 13
  • 3
  • myfile.txt.replace(".txt","") – Daniel Dec 11 '19 at 21:18
  • 1
    There are some answers here https://stackoverflow.com/questions/678236/how-to-get-the-filename-without-the-extension-from-a-path-in-python – chrisbyte Dec 11 '19 at 21:19
  • 2
    Does this answer your question? [How to get the filename without the extension from a path in Python?](https://stackoverflow.com/questions/678236/how-to-get-the-filename-without-the-extension-from-a-path-in-python) – Tomerikoo Dec 11 '19 at 21:20
  • In the future, please find a better title for your post. See: [ask]. – AMC Dec 12 '19 at 02:43

4 Answers4

2

The best way to do it is in the example

import os

filename = 'myfile.txt'

print(filename)
print(os.path.splitext(filename))
print(os.path.splitext(filename)[0])

More info about this very useful builtin module

https://docs.python.org/3.8/library/os.path.html

Alexandr Shurigin
  • 3,921
  • 1
  • 13
  • 25
2

The answers given are totally right, but if you have other possible extensions, or don't want to import anything, try this:

name = file_name.rsplit(".", 1)[0]
Kalma
  • 111
  • 2
  • 15
1

You can use pathlib.Path which has a stem attribute that returns the filename without the suffix.

>>> from pathlib import Path
>>> Path('myfile.txt').stem
'myfile'
Jab
  • 26,853
  • 21
  • 75
  • 114
0

Well if you only have .txt files you can do this

file_name = "myfile.txt"
file_name.replace('.txt', '')

This uses the built in replace functionality. You can find more info on it here!

J_C
  • 329
  • 1
  • 15
  • 2
    What if the file does not end with `.txt`? – chrisbyte Dec 11 '19 at 21:19
  • @chrisbyte you could also split on the "." and just print the 1st result in the list it returns – J_C Dec 11 '19 at 21:21
  • 1
    Periods are legal in file names, and some files can be called `my.file.txt`. It would only return the `my` – chrisbyte Dec 11 '19 at 21:23
  • @chrisbyte the split method returns a list so in that case you can remove the last item in the list and reconstruct the remaining items with a .join() – J_C Dec 12 '19 at 20:46