Python程序无法打开txt文件

问题描述 投票:-1回答:1

我是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打开时打开它

python-2.7
1个回答
0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.