在我的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
Run Code Online (Sandbox Code Playgroud)
问题:
目录和文件的路径并不总是相同,具体取决于我运行脚本的服务器.目录名称的一部分将是创建它的日期时间,即time.strftime("%y%m%d%H%M%S") + "word"如果时间不断变化,我不知道如何调用该目录.我以为我可以用shutil.move()它来创建文件后移动文件,但日期时间戳似乎有问题.
我是初学程序员,老实说我不知道如何处理这些问题.我在考虑将变量分配给目录和文件,但是日期时间让我感到沮丧.
问题:如果文件和子目录的名称/路径不总是相同,如何在子目录中创建文件?
Ant*_*ala 11
将创建的目录存储在变量中.os.mkdir如果该名称存在目录,则抛出.用于os.path.join将路径组件连接在一起(它知道是否使用/或\).
import os.path
subdirectory = datetime + "-dst"
try:
os.mkdir(subdirectory)
except Exception:
pass
for ip in open("list.txt"):
with open(os.path.join(subdirectory, ip.strip() + ".txt"), "a") as ip_file:
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20029 次 |
| 最近记录: |