6

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?

2 Answers 2

15

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:
        ...
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.