rishabh jain rishabh jain - 4 months ago 7
Linux Question

linux and python with filehandling

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

variable='jack'
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:

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


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

You need to pass the variable:

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

or:

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.

So:

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")
       f.write("os.mkdir('{}')".format(variable))

If you want to execute later:

with open('xyz.txt') as f:
   exec(f.read())
Comments