rishabh jain rishabh jain - 1 year ago 63
Linux Question

linux and python with filehandling

If I open Python in Linux and write the following code:

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

then a directory is made with the name jack in the present working directory,

but if I want to use file handling for this 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 xyz.txt file instead of
os.system('mkdir jack')

How can I put this variable inside xyz.txt?

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