Ahmad
Ahmad

Reputation: 3

how to use variable in file path

i have this working code but it doesnt do the whole job at the moment, currently the code creates 30 files and write them too but i couldnt manage yet to rename each file of those 30 files to readme.ini and put it in its folder (which is the DB number shown in list)

what im trying to do is to create those 30 files and place each one of them in its folder which named as its DB number

e.g. the file with info belongs to DB number "5030" should be placed in folder named "5030", all those DB numbers mentioned in the list folders are already created in a folder in my desktop where the path is C:\Users\Administrator\Desktop\readme1\

import datetime

SchoolDB = [5002, 5006, 5020, 5021, 5022, 5025, 5028, 5030, 5102, 5103, 5104, 5105, 5109, 5117, 5119, 5120, 5121, 5126,
        5130, 5131, 5132, 5133, 5134, 5135, 5136, 5137, 5205, 5211, 5238, 5244]
print (SchoolDB)
todayd = datetime.datetime.now().strftime ("%#d/%#m/%Y")
todayt = datetime.datetime.now().strftime ("%H:%M:%S")
for x in SchoolDB:
    dbs = open("%s.ini" % x, 'w+')
   dbs.write("%s \n%s \n\n%s \n%s \n\n%s \n%s \n" % ('[SCHOOL]',x,'[DATE]',todayd,'[TIME]',todayt))

i expect the loop to create readme.ini file with specific info for each DB number in the list and place this readme.ini file in its DB number folder.

Upvotes: 0

Views: 3811

Answers (5)

Chris Larson
Chris Larson

Reputation: 1724

Assuming I understand correctly, you wish to create a series of directories with the values in SchoolDB as their names. Within each one of these, you wish to have a file named readme.ini. Givien those assumptions, the following code will accomplish the task:

import os
import datetime

SchoolDB = [5002, 5006, 5020, 5021, 5022, 5025, 5028, 5030, 5102, 5103, 5104,
5105, 5109, 5117, 5119, 5120, 5121, 5126, 5130, 5131, 5132, 5133, 5134, 5135,
5136, 5137, 5205, 5211, 5238, 5244]

todayd = datetime.datetime.now().strftime ("%#d/%#m/%Y")
todayt = datetime.datetime.now().strftime ("%H:%M:%S")

for number in SchoolDB:
    os.makedirs('{}'.format(str(number)), exist_ok=True)
    with open("{}/readme.ini".format(str(number)), 'w+') as dbs:
        dbs.write("[SCHOOL] \n{} \n\n[DATE] \n{} \n\n'[TIME]' \n{} \n".format(number, todayd, todayt))

A few things to note:

number is a more informative variable name. It's a good habit to develop for readability.

In os.makedirs(), if you're concerned about a directory already existing, perhaps from a previous run, you can set exist_ok=False to fail if the directory does exist. You'll need to handle how to deal with the situation in your code if you choose to do so. As it stands, if the directory already exists, any readme.ini inside it will be overwritten with a new one.

The modern format() approach is also good practice, and your constant names aren't necessary as variables. Simply put them in the string to be formatted, as shown here.

It's always good practice to use the with open() context manager when dealing with files. As it stands, every one of your files remains open until you either dbs.close() or your code exits. This is unnecessary, can lead to complications, and uses more system resources than necessary.

Upvotes: 0

Shadab Ahmed
Shadab Ahmed

Reputation: 576

Move to parent directory

Import os
os.chdir('PARENT_DIRECTORY_PATH')

create new directory for your DB & change directory to your new DB

for x in SchoolDB:
    os.mkdir(x)
    os.chdir(x)
    dbs = open("readme.ini" , 'w+')

Upvotes: 0

thakee nathees
thakee nathees

Reputation: 965

you need to import os module in order to create a folder (with the name of the DB number)and then create the readme.ini file inside the folder (with a relative path) like this

import os
...
for x in SchoolDB:
    folder = os.mkdir("%s"%x) ## this will creare a folder with the name of x
    dbs = file.open("%s/readme.ini"%x,"w+") ## relative path to your file
    dbs.write("now write what ever you want")

Upvotes: 1

chaos
chaos

Reputation: 681

What you're looking for is: dbs = open("{}.ini".format(x), 'w+')

similarly, you want to use "".format() on the string you're outputting. In that case, I find it more readable as:

dbs.write("""[SCHOOL]\n{}\n\n[DATE]\n{}\n\n[TIME]\n{}\n""".format(x, todayd, todayt)

Upvotes: 0

anand_v.singh
anand_v.singh

Reputation: 2838

To use variable filenames use,

filename = '{} hello'.format(varname)

if you want to pass multiple variables to the string use

filename = '{} hello{}'.format(varname1,varname2)

in both cases {} will be replaced by variable values

and then just simply open with filename

Upvotes: 0

Related Questions