从某个位置加载.txt文件,以便我可以读取内容 - 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并编辑内容。

python参考方案

如果只希望用户选择一个.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()

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

Python:同时在for循环中添加到列表列表 - python

我想用for循环外的0索引值创建一个新列表,然后使用for循环添加到相同的列表。我的玩具示例是:import random data = ['t1', 't2', 't3'] masterlist = [['col1', 'animal1', 'an…

查找字符串中的行数 - python

我正在创建一个python电影播放器​​/制作器,我想在多行字符串中找到行数。我想知道是否有任何内置函数或可以编写代码的函数来做到这一点:x = """ line1 line2 """ getLines(x) python大神给出的解决方案 如果换行符是'\n',则nlines …