gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:02 24 4
gpt4 key购买 nike

我对编程还很陌生,我的大学有一项任务。我想要求用户添加一个 .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并编辑内容。

最佳答案

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

from tkinter import filedialog

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

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

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()

关于python - 从某个位置加载 .txt 文件,以便我可以读取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55268271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com