如果文本文件不存在则创建文本文件

Creation of text files if they don't already exist

我正在尝试检查文本文件是否存在,如果不存在则创建它。 我已经通过 TkInter Python 创建了一个工作的多用户登录系统,但需要代码能够存储与登录用户对应的数据。 但是我将 运行 保留在这个错误中:

`Exception in Tkinter callback
Traceback (most recent call last):
  File "D:\Python 3.3.2\Python files\lib\idlelib\run.py", line 109, in main
    seq, request = rpc.request_queue.get(block=True, timeout=0.05)
  File "D:\Python 3.3.2\Python files\lib\queue.py", line 175, in get
    raise Empty
queue.Empty

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\Python 3.3.2\Python files\lib\tkinter\__init__.py", line 1475, in __call__
    return self.func(*args)
  File "D:\Python 3.3.2\A Level Computer Science\programcodetest.py", line 92, in CheckLogin
    LoggedIn()
  File "D:\Python 3.3.2\A Level Computer Science\programcodetest.py", line 137, in LoggedIn
    userfile = nameEL.get()
  File "D:\Python 3.3.2\Python files\lib\tkinter\__init__.py", line 2512, in get
    return self.tk.call(self._w, 'get')
_tkinter.TclError: invalid command name ".44825680"`

这是遇到错误的代码部分:

from tkinter import *
import os

creds = 'tempfile.txt'

def Signup():

    global pwordE
    global nameE
    global roots

    roots = Tk()
    roots.title('Signup')
    intruction = Label(roots, text='Please enter new Username and Password\n')
    intruction.grid(row=0, column=0, sticky=E)

    nameL = Label(roots, text='New Username: ')
    pwordL = Label(roots, text='New Password: ')
    nameL.grid(row=1, column=0, sticky=W)
    pwordL.grid(row=2, column=0, sticky=W)

    nameE = Entry(roots)
    pwordE = Entry(roots, show='*')
    nameE.grid(row=1, column=1)
    pwordE.grid(row=2, column=1)

    signupButton = Button(roots, text='Signup', command=FSSignup)
    signupButton.grid(columnspan=2, sticky=W)
    roots.mainloop()

def FSSignup():
    with open(creds, 'a') as f:
        f.write(nameE.get())
        f.write('\n')
        f.write(pwordE.get())
        f.write("\n")
        f.close()

    roots.destroy()
    Login()

def Login():

    global nameEL
    global pwordEL
    global rootA

    rootA = Tk()
    rootA.title('Login')

    intruction = Label(rootA, text='Please Login\n')
    intruction.grid(sticky=E)

    nameL = Label(rootA, text='Username: ')
    pwordL = Label(rootA, text='Password: ')
    nameL.grid(row=1, sticky=W)
    pwordL.grid(row=2, sticky=W)

    nameEL = Entry(rootA)
    pwordEL = Entry(rootA, show='*')
    nameEL.grid(row=1, column=1)
    pwordEL.grid(row=2, column=1)

    loginB = Button(rootA, text='Login', command=CheckLogin)
    loginB.grid(columnspan=2, sticky=W)

    adduser = Button(rootA, text='Add new user?', command=Signup)
    adduser.grid(columnspan=2, sticky=W)

    rmuser = Button(rootA, text='Delete Users', fg='red', command=Deluser)
    rmuser.grid(columnspan=2, sticky=W)

def CheckLogin():

    global nameEL
    global pwordEL
    global rootA

    with open(creds) as f:
        try:
            data = f.read().splitlines()
            userloc = data.index(nameEL.get())
            pwordloc = data.index(pwordEL.get())
            if nameEL.get() in data:
                if pwordloc == userloc + 1:
                    r = Tk()
                    r.title('Login')
                    r.geometry('150x50')
                    rlbl = Label(r, text='\n Logged In')
                    rlbl.pack()
                    r.destroy()
                    LoggedIn()
                else:
                    rootA.destroy()
                    r = Tk()
                    r.title('Login')
                    r.geometry('150x50')
                    rlbl = Label(r, text='\n[!] Invalid Login')
                    rlbl.pack()
                    r.mainloop()
                    Login()
            else:
                rootA.destroy()
                r = Tk()
                r.title('Login')
                r.geometry('150x50')
                rlbl = Label(r, text='\n[!] Invalid Login')
                rlbl.pack()
                r.mainloop()
                Login()
        except ValueError:
            rootA.destroy()
            r = Tk()
            r.title('Login')
            r.geometry('150x50')
            rlbl = Label(r, text='\n[!] Invalid Login')
            rlbl.pack()
            r.mainloop()
            Login()

def Deluser():
    os.remove(creds)
    rootA.destroy()
    Signup()

def LoggedIn():

    global nameEL
    global pwordEL
    global rootA

    rootA.destroy()
    roots1 = Tk()
    roots1.title('Logged in successfully')
    roots1.geometry("300x300")

    userfile = nameEL.get()
    newuserfile = open(nameEL.get(),".txt", "a")
    #this is where I would like to check the existence of a text file under the current user and if it does not exist create one

if os.path.isfile(creds):
    Login()
else:
    Signup()

如果有任何建议和帮助,我将不胜感激:)

如果指定的名称不存在,您可以使用 'a' 选项自动创建文件:

f = open('filename.txt', 'a')

打开(nameEL.get() + ".txt", "a")