2016-04-17 32 views
0

我正試圖在一個文件夾中創建一個.txt文件,該文件不是腳本正在運行的目錄。我有一個腳本所在的文件夾,我可以在腳本所在的同一目錄中創建文件夾,但不會在該文件夾中創建文本文件。我通常兩個錯誤之一運行:PermissionError: [Errno 13] Permission deniedFileNotFoundError: [Errno 2] No such file or directory:如何創建文本文件在使用python的文件夾中?

這是一個密碼管理器順便說一句,防止五人告訴我,這不是安全的,我知道這一點,這個項目是純粹的教育和我始終使用佔位符。

有這種類似的問題,但他們都對Java或C++ ...

這裏是我的代碼:

def main(): 
    import os 
    import os.path 
    abc = open("userpassfile.txt", "r+") 
    userpassfile = abc.read().strip().split() 
    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 = abc123.read().strip().split() 
        addpass1 = input('What service is the pass') 
        addPass2 = input('What is the password') 
        abc123.write('(' + addpass1 + ',' + addPass2 + ')' + '\n') 

       else: 
        print('hihi') 
      else: 
       print("hehe") 
     else: 
      print('Incorrect password or username!') 
    else: 
     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') 
      os.makedirs(createUser) 
      completeName = os.path.join(save_path, createUser + ".txt") 



main() 

如果您對我的代碼有任何疑問,請隨時問!

回答

2

嘗試open .txt文件中的a模式或w模式。如果以r+模式打開它,則不會創建文件,因爲r+不會創建文件。

'a'創建文件,如果它不存在,但如果它確實存在,它只是添加到它。另一方面,'w'刪除現有的並創建一個新的。我想你想在這裏使用a

編輯:我誤解了這裏的問題。該文件正在創建在錯誤的目錄中。僅供將來參考,如果將文件放入子目錄中,確保在將它們分開時添加"/"

+0

當我嘗試這樣做,它給了我這樣的:回溯(最近最後一次通話): 文件 「keeper.py」,第47行,在 的main() 文件 「keeper.py」 23行,主 huehuehue = abc123.read()。strip()。split() io.UnsupportedOperation:不可讀 –

+0

您可能必須確保文件存在,然後在'r +'模式下打開它。據我所知,您無法以'a'或'w'模式讀取文件,忘記提及這一點。 –

+0

當我在w模式下打開它時,出現同樣的錯誤,就像我在模式中打開它時一樣。它雖然創建文件...它只是不創建該文件夾中的文件。 –

0

import os和import os.path需要位於程序的開頭。例如:

import os 
import os.path 
def main(): 

而不是在main():函數內部。

相關問題