Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 870
hjames Avatar asked Dec 08 '22 13:12

hjames


1 Answers

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