我需要这段代码创建文本文档,但我需要在每次创建新的文本文档时更改名称,例如,在执行代码时,它将创建一个名为“aventura-1.txt”的文本文档,那么为什么要再次执行,名称也将是“aventura-2.txt”等等--“aventura-n.txt”--我怎么能这样做呢?
对不起,我的英语不好,这是我的代码。
import os
def adventure_path ( nombre_aventura) :
if not os. path . isdir (" aventuras ") :
os. mkdir (" aventuras ")
return " aventuras/ %s" %nombre_aventura
archivo = open ( adventure_path ("aventura-n.txt") ,"w")
print "hi"
print "bye"
archivo . close ()
发布于 2016-06-21 18:24:34
你可以用我写过的代码帮你修改一下.
它将:
check
特定文件夹中的每个文件split
这些文件的名称在"."
和"-"
上,所以我们只能捕获.txt
名称的数字部分(我假设您将有一个只包含"aventura-n.txt“的特定文件夹,名为”Aventura-n.txt“)add
到列表get
数字列表的max
值add +1
代码:
import os
nums = []
for item in os.listdir('path_to_folder'):
a = item.split(".")[0]
b = a.split("-")[1]
c = int(b)
nums.append(c)
next_num = max(nums) + 1
print next_num
https://stackoverflow.com/questions/37957208
复制