-1

I have the following variable:

input_file = 'gs://tinydancer/test_files/GoogleSheetsandPython_1min.flac'

I would like to use the GoogleSheetsandPython_1min portion of the input_file variable to name a .txt file. That will be created later in the script.

I would also like to append .txt to the end the file name.

Here is how I am achieving this currently:

text_file = open("GoogleSheetsandPython_1min.txt", "a")

By simply hardcoding it in, I want to make this automated. So that once input file was set, you could use this to change the output .txt file name accordingly. I have done some research on this but have not found good way to do this so far.

martineau
  • 119,623
  • 25
  • 170
  • 301
EliC
  • 235
  • 1
  • 6
  • 16
  • Try this [answer](https://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format) – Bug Jul 21 '17 at 01:54

3 Answers3

0

You can split the string along the / and get the last item and then append ".txt" like this:

>>> input_file.split('/')[-1] + '.txt'
'GoogleSheetsandPython_1min.flac.txt'

In case I misunderstood and you want to replace .flac with .txt, you can just do another split on . and then append the .txt.

>>> input_file.split('/')[-1].split('.')[0] + '.txt'
'GoogleSheetsandPython_1min.txt'

Regex solution:

import re

>>> re.search('[^/][\\\.A-z0-9]*$', input_file).group()
'GoogleSheetsandPython_1min.flac'

Then you can split on the . to get rid of the file extension.

Cory Madden
  • 5,026
  • 24
  • 37
  • You could use `.rsplit("/", 1)[1]` instead - a bit more efficient. – Hugh Bothwell Jul 21 '17 at 01:52
  • Yes, thats what I am looking for in the `text_file` variable, any suggestions on how to remove the front of that `input_file`? This: `gs://tinydancer/test_files/` I was thinking something along the lines of `input_file.remove[?] but I wasn't sure on what index to use since it is "technically" all one word. Or is it? – EliC Jul 21 '17 at 01:52
  • I don't think I understand. Isn't that what I just showed you? – Cory Madden Jul 21 '17 at 01:55
  • Or you could use regex to get the filename `re.search('[^/][\.A-z0-9]*$', input_file).group()` outputs: `'GoogleSheetsandPython_1min.flac'` – Cory Madden Jul 21 '17 at 01:56
  • @EliC strings are immutable – Cory Madden Jul 21 '17 at 01:59
0

using os.path

import os

input_file = 'gs://tinydancer/test_files/GoogleSheetsandPython_1min.flac'
input_file = os.path.splitext(os.path.basename(input_file))[0] + '.txt'
ewwink
  • 18,382
  • 2
  • 44
  • 54
0

you can use os.path.basename

import os

input_file = 'gs://tinydancer/test_files/GoogleSheetsandPython_1min.flac'
new_file = os.path.basename(input_file).replace("flac", "txt")
text_file = open(new_file, "a")