我有格式的文件名:
Unix3145_report.txt
Unix5694_report.txt
Unix3452_report.txt
Unix1232_report.txt
Unix5492_report.txt
差异只有四位数字。我正在读取所有这些文件并将其中的文本转换为其他文件。
目前我从命令行进行参数解析并提供完整的文件名。
有没有办法,我可以在我的脚本中创建文件名,只插入用户的数字?像os.join.path
这样的东西用于创建文件路径
答案 0 :(得分:3)
os.path.join
用于加入路径,而不是创建文件名。
文件名是一个简单的字符串,您可以在创建任何其他字符串时创建它。示例 -
num = 3145 #This can be the number inputted from user or some other place
filename = "Unix{}_report.txt".format(num)
print(filename)
>>> Unix3145_report.txt
然后,如果需要,可以使用os.path.join
创建文件的完整路径。
答案 1 :(得分:0)
只需连接字符串
fileName = "Unix"+userInput+"_report.txt"
答案 2 :(得分:0)
另一种方法是%
- 格式化
filename = 'Unix%s_report.txt' % num
%s
(对于字符串),您可以使用%d
来确保num
是数字类型