如何访问存储在变量名下的文本文件

How to access a text file stored under a variable name

尝试从 Python 访问外部文本文件时,我在尝试简单地查看文件内容和尝试添加到文件时遇到了几个问题。所涉及的程序部分采用用户名并在该用户名下创建一个文本文件(如果尚不存在)。使用Create()函数时,遇到如下TypeError:

Exception in Tkinter callback
Traceback (most recent call last):
  File "D:\Python 3.3.2\A Level Computer Science\Whosebugsolution.py", line 48, in View
    with open(userfile, 'r') as u:
FileNotFoundError: [Errno 2] No such file or directory: 'name.txt'

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\Whosebugsolution.py", line 91, in Add
    u.write(addText.get())
TypeError: get() missing 1 required positional argument: 'index1'

这是遇到错误的代码:

from tkinter import *
import os

def Login():

    global nameEL
    global rootA

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

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

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

    nameEL = Entry(rootA)
    nameEL.grid(row=1, column=1)

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

def LoggedIn():

    global userfile

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

    userfile = nameEL.get() + '.txt'

    View1 = Button(roots1, text='View', command=View)
    View1.grid(columnspan=10, sticky=W)
    View1.pack(fill = 'x')

    Create1 = Button(roots1, text='Create', command=Create)
    Create1.grid(columnspan=10, sticky=W)
    Create1.pack(fill = 'x')

def View():

    global userfile

    try:
        with open(userfile, 'r') as u:
            print(u.read())
    except FileNotFoundError:
        r = Tk()
        r.title('View')
        r.geometry('300x50')
        rlbl = Label(r, text='\n[!] Theres nothing to see here [!]')
        rlbl.pack()
        r.mainloop()
        LoggedIn()
    except ValueError:
        r = Tk()
        r.title('View')
        r.geometry('300x50')
        rlbl.pack()
        r.mainloop()
        LoggedIn()

def Create():

    global addText
    global rootC

    rootC = Tk()
    rootC.title('Lets add some information')
    instruction = Label(rootC, text='Please enter the information you would like to add\n')
    instruction.grid(row=0, column=0, sticky=W)

    newText = Label(rootC, text='info: ')
    newText.grid(row=1, column=0)

    addText = Text(rootC)
    addText.grid(row=2, column=0)

    addButton = Button(rootC, text='Add', command=Add)
    addButton.grid(columnspan=2, sticky=W)
    addButton.grid(row=3, column=0)

def Add():

    global userfile

    with open(userfile, 'a') as u:
        u.write(addText.get())
        u.write('\n')

        rootC.destroy()
        LoggedIn()

Login()

我会这样做:

def LoggedIn():

    global userfile

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

    userfile = nameEL.get() + '.txt'
    #and the tkinter widgets

此代码 userfile = open(nameEL.get() + '.txt', 'a') 有点奇怪,您正在使用 open 命令创建一个对象,稍后您将其用作字符串。你只需要 userfile 是一个字符串,而不是一个命令。然后,您可以使用它打开文件(见下文)

def View():

    global userfile

    try:
        with open (userfile, 'r') as u:
            print (u.read())
    except FileNotFoundError: #file doesn't exist
        r = Tk()
        r.title('View')
        r.geometry('300x50')
        rlbl = Label(r, text='\n[!] This file doesn't exist [!]')
        rlbl.pack()
        r.mainloop()
        LoggedIn()
    except ValueError: #some error when reading
        r = Tk()
        r.title('View')
        r.geometry('300x50')
        rlbl = Label(r, text='\n[!] Problem when reading the file [!]')
        rlbl.pack()
        r.mainloop()
        LoggedIn()

在这里,print(userfile.read()) 无法正常工作,因为您使用 append 模式创建了userfile(也许还有其他问题)

最后

def Add():
    global userfile

    with open(userfile, 'a') as u:
        u.write(addText.get()) #don't forger the .get ()
        u.write('\n')

    rootC.destroy()
    LoggedIn()

在这里,您试图在文件中写入一个 Entry 对象,Python 不喜欢这样。您只需要添加 .get() 以便它写入 Entry 对象 addText 中的内容。 这里还有一个错误:当使用 with () 命令时,您不需要关闭文件,它会自动完成。 可能仍然存在问题,但文件应该可以正常工作。

编辑: 使用 Text 小部件时,get() 命令比仅使用 Entry 小部件时需要更多参数 你可以使用这个:

u.write (addText.get('1.0', END))