从某个位置加载.txt文件,以便我可以读取内容

时间:2019-03-20 18:56:41

标签: python

我对编程很陌生,我有一个要完成的大学工作。 我想请用户添加一个.txt文件,以便我可以某种方式进行编辑(复制内容)并返回已编辑的内容。我已经尝试了一些解决方案,但遇到了麻烦。

from tkinter import *
from tkinter import filedialog
import os

filename = filedialog.askopenfile()
print(filename.name) 
# I have the location of the loaded file C:/Users/...Desktop/text.txt

nameOfFile = os.path.basename(filename.name)
print(nameOfFile) 
# Here i take the text.txt name 

------

here i want the code to load this text.txt 
file knowing its location so i can have acces to it and read it.

-------

fileReadyToRead = open(nameOfFile, 'r')
file_contents = fileReadyToRead.read()
print(file_contents)

fileReadyToRead.close()

结论:我想请用户在程序中添加.txt并编辑内容。

1 个答案:

答案 0 :(得分:0)

如果只希望用户选择一个.txt文件,然后打印其内容,则效果很好:

from tkinter import filedialog

filename = filedialog.askopenfile()
fileReadyToRead = open(filename.name, 'r')
file_contents = fileReadyToRead.read()
print(file_contents)
fileReadyToRead.close()

如果您要打开一个允许用户打开,编辑和保存.txt文件的TKinter实例,则可以这样做:

from tkinter import *
from tkinter import filedialog
import codecs


class App():
    def __init__(self, parent):
        self.root = parent
        self.entry = Text(self.root)
        self.entry.pack() 
        self.button1 = Button(self.root, text='Load', command=self.load_txt)
        self.button1.pack()
        self.button2 = Button(self.root, text='Save', command=self.save_txt)
        self.button2.pack()

    def run(self):
        self.root.mainloop() 

    def load_txt(self):   
        self.filename = filedialog.askopenfile()
        with codecs.open(self.filename.name, 'r') as f:
            file_contents = f.read()
            self.entry.insert(INSERT,file_contents) 

    def save_txt(self):
        text = self.entry.get("1.0",END) 
        with codecs.open(self.filename.name, 'w') as f:
            f.write(text)


app = App(Tk())
app.run()