hjames
hjames

Reputation: 449

Create file in sub directory Python?

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.

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.

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?

Upvotes: 6

Views: 36075

Answers (2)

user2708513
user2708513

Reputation: 1

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")

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

Upvotes: 0

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

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:
        ...

Upvotes: 15

Related Questions