-3

I'm having an issue that is probably more easy than I am making it out to be. (I am in an intro level programming class)

Basically I am writing a program where I ask a user for a file name, I read info from the file before sorting it in a list and writing it somewhere else. The assignment wants us to ask user for the file name to read from. If the user enters the file name with the '.txt', we carry on with the processing. If they do not, we must add the '.txt' before continuing on. I know how to add the '.txt' to the file name if they did not include it, but I can not figure out how to check first to see if they did.

How do I go about first checking to see if the user wrote the file name with the extension?

I am assuming it has something to do with an if/else statement but I have been baffled.

Thank you

TX_RocketMan
  • 3
  • 1
  • 3

3 Answers3

2

To check + add the extension:

import os.path

if os.path.splitext(filename)[1] != '.txt':  # Ending is not '.txt'.
   filename += '.txt'

Using os.path.splitext to split the base-name and the extension.

anon582847382
  • 19,907
  • 5
  • 54
  • 57
0

You can use the endswith (without any additional imports):

fileName += ".txt" if not fileName.endswith('.txt') else ""

If you want to correct the extension you might want to look at os.splitpath

Tejas Pendse
  • 551
  • 6
  • 19
0

You probably have the filename stored in a str object (ie, a string). Python documents all the operations you can perform on a str object. One of those operations is endswith - this will tell you whether the string object ends with a particular substring.

So if you have the filename stored in a variable called my_filename, you could do the following:

has_extension = my_filename.endswith('.txt')

has_extension will be true if my_filename ends with '.txt', and false otherwise.

Python's odcumentation is fantastic, I would keep a bookmark to it for reference for situations like this

Elliott
  • 1,336
  • 1
  • 13
  • 26