rishabh jain rishabh jain - 1 year ago 84
Python Question

Filehandling with Python on Linux OS

I have written the following code on Python on Linux OS:

import os
os.system('mkdir '+variable)

Then a directory is made with the name jack on the present working directory.

However, if I want to use file handling for the same purpose

f=open('xyz.txt', mode="w")
f.write("import os")
f.write("os.system('mkdir '+variable)")

then the code
os.system('mkdir '+variable)
is appended as it is in the
file instead of
os.system('mkdir jack')

Please help me to get this variable inside the file

Answer Source

You need to pass the variable:

f.write("os.system(mkdir {})".format(variable))


f.write("os.system(mkdir " + variable + ")"))

You are writing the literal string "+ variable" as you have it all inside the double quotes. You also have a problem with f.write("import os") as you added no newline so all your data would be on one line so if you plan on executing that code later add a newline f.write("import os\n") and remember to strip it off later if you are reading line by line.


with open('xyz.txt', w) as f:
   f.write("import os\n")
   f.write("os.system(mkdir {})".format(variable))

If you plan on executing the code later, add single quotes around the name:

 f.write("os.system('mkdir {}')".format(variable))    

You can also forget using system at all and just use os.mkdir:

  with open('xyz.txt', w) as f:
       f.write("import os\n")

If you want to execute later:

with open('xyz.txt') as f:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download