Create file in another directory that is not the current one (Python)

0

I want to create the file inside the folder of line 1 that is created at the same level where the file.txt is created

os.mkdir(svnombreRP.get())
archi = open('%s.txt' % svnombreRP.get(), 'wb')
archi.close()

I tried to put it like this:

os.mkdir(svnombreRP.get())
archi = open('%s/%s.txt' % svnombreRP.get(), 'wb')
archi.close()

Since I want the file to be named like the directory, the name is given by the function svnombreRP.get () but it is not saved in the directory, it is stored next to the directory.

    
asked by Barkalez 23.10.2016 в 00:40
source

1 answer

2

If I have not misunderstood you, what you want is to create a folder inside the directory where your script is hosted and within that folder the .txt is created. The file and the folder have the same name (given by svnombreRP.get() ).

The use of the string operator % , if I remember correctly, was marked as deprecated in Python 3 and is supposed to disappear in the future. I do not know what version you use but I recommend using str.format() for this kind of thing (it works in Python 2.7 and 3.x):

os.mkdir(svnombreRP.get())
archi = open('{0}/{0}.txt'.format(svnombreRP.get()), 'wb')
archi.close()

This should work. By the way, mkdir() will produce an error if the directory already exists, you must take it into account.

    
answered by 23.10.2016 / 01:10
source