【发布时间】:2011-02-23 09:49:46
【问题描述】:
假设从index.py 使用CGI,我有发布文件foo.fasta 来显示文件。我想在显示文件中将foo.fasta 的文件扩展名更改为foo.aln。我该怎么做?
【问题讨论】:
标签: python rename file-extension
假设从index.py 使用CGI,我有发布文件foo.fasta 来显示文件。我想在显示文件中将foo.fasta 的文件扩展名更改为foo.aln。我该怎么做?
【问题讨论】:
标签: python rename file-extension
使用pathlib.Path的优雅方式:
from pathlib import Path
p = Path('mysequence.fasta')
p.rename(p.with_suffix('.aln'))
【讨论】:
.with_suffix(),属性.suffix和.suffixes应该有setter。
os.path.splitext(), os.rename()
例如:
# renamee is the file getting renamed, pre is the part of file name before extension and ext is current extension
pre, ext = os.path.splitext(renamee)
os.rename(renamee, pre + new_extension)
【讨论】:
os.rename(root, root + new_extension) 应改为 os.rename(renamee, root + new_extension)
import os
thisFile = "mysequence.fasta"
base = os.path.splitext(thisFile)[0]
os.rename(thisFile, base + ".aln")
其中 thisFile = 您要更改的文件的绝对路径
【讨论】:
base, _ = os.path.splitext(thisFile) 更惯用。
从 Python 3.4 开始,有 pathlib 内置库。所以代码可能是这样的:
from pathlib import Path
filename = "mysequence.fasta"
new_filename = Path(filename).stem + ".aln"
https://docs.python.org/3.4/library/pathlib.html#pathlib.PurePath.stem
我喜欢 pathlib :)
【讨论】:
new_filename = f"{Path(filename).stem}.aln" ???
p.parent / (p.stem + '.aln') 会给你一个新的路径。
使用这个:
os.path.splitext("name.fasta")[0]+".aln"
以下是上述的工作原理:
splitext 方法将名称与创建元组的扩展分开:
os.path.splitext("name.fasta")
创建的元组现在包含字符串“name”和“fasta”。 然后您只需要访问作为元组的第一个元素的字符串“name”:
os.path.splitext("name.fasta")[0]
然后您想为该名称添加一个新的扩展名:
os.path.splitext("name.fasta")[0]+".aln"
【讨论】:
正如 AnaPana 提到的,pathlib 在 python 3.4 中更加新和更容易,并且有新的 with_suffix 方法可以轻松处理这个问题:
from pathlib import Path
new_filename = Path(mysequence.fasta).with_suffix('.aln')
【讨论】:
使用 pathlib 并保留完整路径:
from pathlib import Path
p = Path('/User/my/path')
new_p = Path(p.parent.as_posix() + '/' + p.stem + '.aln')
【讨论】:
new_p = Path(p.with_suffix('').as_posix() + '.aln')
遗憾的是,我遇到了一个文件名上有多个点的情况,splittext 不能很好地工作......我的解决方法:
file = r'C:\Docs\file.2020.1.1.xls'
ext = '.'+ os.path.realpath(file).split('.')[-1:][0]
filefinal = file.replace(ext,'')
filefinal = file + '.zip'
os.rename(file ,filefinal)
【讨论】:
>> file = r'C:\Docs\file.2020.1.1.xls'
>> ext = '.'+ os.path.realpath(file).split('.')[-1:][0]
>> filefinal = file.replace(ext,'.zip')
>> os.rename(file ,filefinal)
重复扩展的错误逻辑,示例:'C:\Docs\.xls_aaa.xls.xls'
【讨论】: