Create file without knowing directory? Python

Asked

Viewed 710 times

0

It is known that it is possible to create a new file through Python through file_create = open(r'C:\Diretório\Diretório...\FileName', 'w'). However, it is necessary to indicate where this file will be created on the computer.

If we wanted to create a file on an unknown computer that would download the Python program, how would that be possible? Considering that to originate content that stays in a specific location and/or explanation on the computer (Desktop or some folder), it is necessary the three elements that precede the 'Desktop' in C: Users Windows 7 Desktop: the 'C', the 'Users', and the username used.

Are there any general commands? Or ask the user where he wants the data to be?

1 answer

2


Hello,

You can get the computer’s user name from the system using getpass. See:

import getpass
usuario = getpass.getuser()

Then you can try something like this:

file_create = open("C:\\Users\\" + usuario + "\\Desktop\\filename", "w")
  • Thank you! A general question: C: Users will be the same for every Windows computer, or it may vary as well?

  • 1

    I at least never saw it vary. In theory it is always supposed to be C: Users..., but I could not give 100% warranty.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.