在我的Python脚本中,我需要在一个子目录中创建一个新文件而不更改目录,并且需要从当前目录中不断编辑该文件。
我的代码:os.mkdir(datetime+"-dst")
for ip in open("list.txt"):
with open(ip.strip()+".txt", "a") as ip_file: #this file needs to be created in the new directory
for line in open("data.txt"):
new_line = line.split(" ")
if "blocked" in new_line:
if "src="+ip.strip() in new_line:
#write columns to new text file
ip_file.write(", " + new_line[11])
ip_file.write(", " + new_line[12])
try:
ip_file.write(", " + new_line[14] + "\n")
except IndexError:
pass
问题:
目录和文件的路径并不总是相同的,这取决于运行脚本的服务器。目录名的一部分将是创建目录的日期时间,即time.strftime("%y%m%d%H%M%S") + "word",如果时间不断变化,我不确定如何调用该目录。我以为我可以在文件创建后使用shutil.move()来移动它,但是日期时间戳似乎带来了问题。
我是一个初学者,我真的不知道如何解决这些问题。我在考虑给目录和文件分配变量,但日期时间让我很困惑。
问题:如果文件和子目录的名称/路径不总是相同,如何在子目录中创建文件?