更改文件扩展名和跟踪更改

2024-07-01 07:23:36 发布

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

我想将文件列表中的文件扩展名(Python语言)从“.hpp”更改为“.h”。在我仅对具有该扩展名的文件进行这些更改之后,我想创建一个名为newfilenames的新列表

我曾试图创建一个有效的程序,但我似乎无法完全理解这个问题。到目前为止,我试图找到一个解决方案

# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
filenames2 = ".".join(filenames)
filenames3 = filenames2.split(".")
filenames4 = list(enumerate(filenames3))
for index, item in filenames4:
    if index % 2 != 0 and item == "hpp":
        item = 'h'

Tags: 文件程序语言列表indexasoutitem
3条回答
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
changed_filenames = []

# loop over all the filenames
for filename in filenames:
    # does this file name end in .hpp ?
    if filename.endswith(".hpp"):
        # make a new filename, omitting the final two characters
        filename = filename[:-2]
    # append the filename to the new list
    changed_filenames.append(filename)
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]

renamed = []
newnames = []

for filename in filenames:
    if filename.split(".")[1] == 'hpp':
        renamed.append(filename)
        newnames.append(filename.split(".")[0]+".h")

print (renamed)
print (newnames)

输出:

['stdio.hpp', 'sample.hpp', 'math.hpp']
['stdio.h', 'sample.h', 'math.h']

只需尝试在列表中使用内置方法“replace”

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
new = [name.replace(".hpp",".h") for name in filenes]
print(new)
>>> ["program.c", "stdio.h", "sample.h", "a.out", "math.hpp", "hpp.out"]

相关问题 更多 >

    热门问题