【发布时间】:2016-04-29 20:35:57
【问题描述】:
我正在学习 Python,我的任务是:
- 在目录中每个名称的开头添加“file_”
- 更改扩展名(目录当前包含 4 种不同的类型:.py、.TEXT、.rtf、.text)
我有很多文件,都有不同的名称,每个文件有 7 个字符长。我能够更改扩展名,但感觉非常笨拙。我很肯定有一种更简洁的方式来编写以下内容(但它的功能,所以没有抱怨):
import os, sys
path = 'C:/Users/dana/Desktop/text_files_2/'
for filename in os.listdir(path):
if filename.endswith('.rtf'):
newname = filename.replace('.rtf', '.txt')
os.rename(filename, newname)
elif filename.endswith('.py'):
newname = filename.replace('.py', '.txt')
os.rename(filename, newname)
elif filename.endswith('.TEXT'):
newname = filename.replace('.TEXT', '.txt')
os.rename(filename, newname)
elif filename.endswith('.text'):
newname = filename.replace('.text', '.txt')
os.rename(filename, newname)
我还有一点问题:
- 脚本当前必须在我的目录中才能运行。
-
我不知道如何在每个文件名的开头添加“file_”[你会认为这很容易]。我尝试将 newname 声明为
newname = 'file_' + str(filename)然后声明文件名未定义。
对于我现有的两个问题的任何帮助将不胜感激。
【问题讨论】:
-
newname = 'file_' + filename应该可以工作。您不需要str(),因为filename已经引用了一个字符串,但即使这样也应该有效。也许你在循环之外尝试过? -
你说得对,它在我的循环之外
-
另一条评论:发布代码时请注意缩进。你知道它在 Python 中很关键。例如,显示的代码不会按原样编译。
标签: python file-handling