Python程序无法打开txt文件

时间:2016-04-08 21:47:34

标签: python-2.7

我是python的新手,我正在尝试创建一个密码管理器。 问题是,当我通过IDLE或Pycharm运行它时,我的程序工作正常 但是当它直接从Windows运行时它停止运行,当它到达我导入存储密码的文件的行时。

import time

user = raw_input("Username: ")
pw = raw_input("Password: ")
if user == "PrOoOg" and pw == "aka443":
    def add_acc_func(acc, user, pw):
        database.write("\nAccount: ")
        database.write(acc)
        database.write("    Username: ")
        database.write(user)
        database.write("    Password: ")
        database.write(pw)
        database.close()


    def print_database_func():
        for lines in database.readlines():
            print lines.strip('\n')
        database.close()

    user_input = raw_input('Press "A" to add a new account\nPress "M" to modify and existing account\n'
                            'Press "D" to delete and existing account\nPress "S" to show all accounts and passwords\n')
    user_choice = user_input.lower()
    if user_choice == "a":
        database = open("source.txt", "a") #Everything worked fine when i deleted this line
        acc_to_add = raw_input("Write the name of the site or service: ").lower()
        acc_to_add_user = raw_input("Write the username or email you want to set for that account: ")
        acc_to_add_pw = raw_input("Write the password you want to set to that account: ")
        add_acc_func(acc_to_add, acc_to_add_user, acc_to_add_pw)
        print "Account added"


    if user_choice == "s":
        database = open("source.txt", "r") #Everything worked fine when i deleted this line
        print_database_func()

    raw_input("Press Enter to quit")
else:
    print ("Wrong username or password")
    time.sleep(3)

我试图删除导入文本文件的行并且它有效。 我不知道为什么代码在从Windows打开时无法打开文件,并且可以在从IDLE或Pycharm打开时打开它

1 个答案:

答案 0 :(得分:0)

“当我从Windows运行它时它就崩溃了(右键单击==>用==> python.exe打开)”

执行此操作时,工作目录为C:\ Windows \ system32。您很可能没有此目录的写权限。使用其他方法运行脚本时,工作目录很可能是包含脚本的目录。您需要更改为您具有写入权限的目录。 以下是使用当前用户的Documents文件夹的示例:

import os dir = os.path.expanduser('~/Documents') os.chdir(dir)

相关问题