如何从变量中删除字符串的一部分?

2024-10-03 04:33:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下变量:

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

我想使用input文件变量的GoogleSheetsandPython_1min部分来命名.txt文件。 稍后将在脚本中创建。你知道吗

我还想在文件名后面加上.txt。你知道吗

以下是我目前是如何做到这一点的:

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

通过简单的硬编码,我想让它自动化。因此,一旦设置了输入文件,就可以使用它相应地更改output.txt文件名。我对此做了一些研究,但到目前为止还没有找到好的方法。你知道吗


Tags: 文件texttesttxt脚本gsinput文件名
3条回答

您可以使用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")

您可以沿着/分割字符串并获取最后一项,然后像这样附加“.txt”:

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

如果我误解了,您想用.txt替换.flac,您可以对.进行另一次拆分,然后附加.txt。你知道吗

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

正则表达式解决方案:

import re

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

然后可以在.上拆分以除去文件扩展名。你知道吗

使用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'

相关问题 更多 >