FileNotFoundError:[Errno 2]没有这样的文件或目录:

时间:2013-09-09 06:04:12

标签: python file createfile

count = 0
answer = ""
pass_pool={"CSRP":"","pos":"","erp":"","comverse":"","miki":"","citrix":""}
name = ""


def program_start():
    answer = input('Do you want to make some TXT with the same passwords? y\\n :')
    count = int(input('How many TXT files do you want to make?'))
    name = input('Enter the hot user id:')
    name = name+".TXT"
    password_collector() # collect password to pass_pool dictionary
    create_file() #create TXT file. it has to be in capital "TXT" 
    #for the safe program.

def create_file():
    newTXT = open(name, "w")
    newTXT.write(name + "\n \n" )
    for system , password in pass_pool.items():
        newTXT.write(system + ":" + password )
    newTXT.close()

我明白了:

File "C:\Python33\mypy\txt creator.py", line 16, in create_file
newTXT = open(name, "w")
FileNotFoundError: [Errno 2] No such file or directory:

从我在google上看到的这个错误意味着找不到错误的路径或文件。但我查看了sys.path并在我的路径中看到了"C:\Python33\mypy",并使用"w"创建了该文件,因此它应该可以正常工作。

当我在shell中只使用create_file()函数时,它没有问题。

1 个答案:

答案 0 :(得分:2)

name中设置program_start的值时,Python会为该函数的作用域创建一个本地变量name,这会掩盖全局name,因此全局值保持不变。在create_file中,您使用未更改的全局name,其等于"",并且打开名为""的文件会给您一个错误。

快速和肮脏的修复将添加

global name

program_start的开头。但是编写

更清楚
count = 0
answer = ""
pass_pool={"CSRP":"","pos":"","erp":"","comverse":"","miki":"","citrix":""}

def program_start():
    answer = input('Do you want to make some TXT with the same passwords? y\\n :')
    count = int(input('How many TXT files do you want to make?'))
    name = input('Enter the hot user id:')
    name = name+".TXT"
    password_colector() # collect password to pass_pool dic
    create_file(name) #create TXT file. it has to be in capital "TXT"
    #for the safe pogram.

def create_file(name):
    newTXT = open(name, "w")
    newTXT.write(name + "\n \n" )
    for system , password in pass_pool.items():
        newTXT.write(system + ":" + password )
    newTXT.close()