rishabh jain
rishabh jain

Reputation: 440

Filehandling with Python on Linux OS

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

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

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')

Please help me to get this variable inside the file xyz.txt!

Upvotes: 2

Views: 70

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

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())

Upvotes: 1

Related Questions