How to create a file within a directory?

Asked

Viewed 112 times

-1

import os

def main():
    checkDir = str(input('Escoha o diretório do arquivo Python: '))
    if os.path.exists(checkDir):
        print('O diretório existe!')
        print()
        nameDir = str(input('Digite o nome do novo arquivo: '))
if __name__ == '__main__':
    main()

Since I could create a "file" inside a python directory (the user speaks the name of the directory, he checks if the directory exists and if it exists creates the file with the name said by the user)?

2 answers

2


From version 3.4 of Python, it is recommended to use the library pathlib to work with directories and files.

from pathlib import Path

directory = Path('test')

if directory.exists():
    file = directory / 'egg.txt'
    file.touch()

If the directory test the file will be created egg.txt within it.

1

f = open(checkDir+'/'+nameDir , "w")
f.write("") # se quiser escrever algo dentro do arquivo, aqui entre as aspas
f.close()

Try it like this, it usually works.

Browser other questions tagged

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