在子目录Python中创建文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18388368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:37:04  来源:igfitidea点击:

Create file in sub directory Python?

pythonpython-3.x

提问by hjames

In my Python script, I need to create a new file in a sub directory without changing directories, and I need to continually edit that file from the current directory.

在我的 Python 脚本中,我需要在不更改目录的情况下在子目录中创建一个新文件,并且我需要从当前目录不断编辑该文件。

My code:

我的代码:

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

Problems:

问题

The path for the directory and file will not always be the same, depending on what server I run the script from. Part of the directory name will be the datetime of when it was created ie time.strftime("%y%m%d%H%M%S") + "word"and I'm not sure how to call that directory if the time is constantly changing. I thought I could use shutil.move()to move the file after it was created, but the datetime stamp seems to pose a problem.

目录和文件的路径并不总是相同的,这取决于我从哪个服务器运行脚本。目录名称的一部分将是创建它的日期时间,即time.strftime("%y%m%d%H%M%S") + "word",如果时间不断变化,我不确定如何调用该目录。我以为我可以shutil.move()在创建文件后使用它来移动文件,但日期时间戳似乎有问题。

I'm a beginner programmer and I honestly have no idea how to approach these problems. I was thinking of assigning variables to the directory and file, but the datetime is tripping me up.

我是一名初级程序员,老实说我不知道​​如何解决这些问题。我正在考虑为目录和文件分配变量,但日期时间让我感到困惑。

Question: How do you create a file within a sub directory if the names/paths of the file and sub directory aren't always the same?

问题:如果文件和子目录的名称/路径不总是相同,如何在子目录中创建文件?

采纳答案by Antti Haapala

Store the created directory in a variable. os.mkdirthrows if a directory exists by that name. Use os.path.jointo join path components together (it knows about whether to use /or \).

将创建的目录存储在变量中。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:
        ...

回答by user2708513

first convert the datetime to something the folder name can use something like this could work mydate_str = datetime.datetime.now().strftime("%m-%d-%Y")

首先将日期时间转换为文件夹名称可以使用这样的东西可以工作 mydate_str = datetime.datetime.now().strftime("%m-%d-%Y")

then create the folder as required - check out Creating files and directories via PythonJohnf

然后根据需要创建文件夹 - 查看 通过 PythonJohnf创建文件和目录