Ari Madian Ari Madian - 2 years ago 189
Python Question

How to create a text file In a folder using python?

I am trying to create a .txt file in a folder which is not the directory the script is being run from. I have a folder where the script is, and I am able to create the folder in the same directory the script is in but It won't create the text file in the folder. I usually run in to one of two errors:

PermissionError: [Errno 13] Permission denied
FileNotFoundError: [Errno 2] No such file or directory:

This is for a password keeper btw, and to prevent five people telling me it's not secure, I am aware of this, this project is purely educational and I always use placeholders.

There are similar questions to this but they are all for java or c++...

Here is my code:

def main():
import os
import os.path
abc = open("userpassfile.txt", "r+")
userpassfile =
actCheck = input('Do you already have an account?')
if (actCheck == 'Yes' or actCheck == 'yes'):
loginUser = input('What is your username?')
loginPass = input('What is yout password?')
if (loginUser and loginPass in userpassfile):
dirCheck = input('Account Settings? [y/n]')
if (dirCheck == 'y' or dirCheck == 'Y'):
print('This function is not working yet!')
addpassCheck = input('Would you like to add a password?')
if (addpassCheck == 'yes' or addpassCheck == 'Yes'):
abc123 = open(loginUser + '.txt', "r+")
huehuehue =
addpass1 = input('What service is the pass')
addPass2 = input('What is the password')
abc123.write('(' + addpass1 + ',' + addPass2 + ')' + '\n')

print('Incorrect password or username!')
createAct = input('would you like to create one?')
if (createAct == 'Yes' or createAct == 'yes'):
save_path = 'C:/Users/Ari Madian/Desktop/Scripts/Python Scripts/Python Password Project'
createUser = input('What would you like your username to be?:')
createPass = input('What would you like your password to be?:')
abc.write(createUser + '\n')
abc.write(createPass + '\n')
completeName = os.path.join(save_path, createUser + ".txt")


If you have any questions about my code, feel free to ask!

Answer Source

Try to open the .txt file in a mode or w mode. If you open it in r+ mode the file will not be created since r+ does not create a file.

'a' creates the file if it does not exist but if it does exist it simply adds to it. 'w', on the other hand, deletes the existing one and creates a new one. I think you want to use a here.

EDIT: I misunderstood the question here. The file was being created in the wrong directory. Just for future reference, if putting a file in a subdirectory, make sure to add "/" when seperating them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download