读取文本文档并将其转换为字符串

时间:2017-09-14 00:24:10

标签: python python-3.x runtime-error traceback

我正在尝试制作一个读取指定文本文档的基本脚本,要求替换一串字符以及替换它,然后保存它:

from tkinter import Tk, filedialog
from tkinter.filedialog import askopenfilename

Tk().withdraw()
    def OpenFile():
    fileName = askopenfilename(initialdir="C:/Users", filetypes = (("Text File", "*.txt"),("All Files","*.*")), title = "Open a document.")
    with open(fileName, 'r') as f:
        textFile = f.read()

OpenFile()
print(textFile)

运行脚本并选择文件

时出错
Traceback (most recent call last):
  File "C:\Users\****\Documents\Python\Find and Replace\replace.py", line 11, in <module>
print(textFile)
NameError: name 'textFile' is not defined

1 个答案:

答案 0 :(得分:-2)

游戏:找到不同的东西:

from tkinter import Tk, filedialog
from tkinter.filedialog import askopenfilename

Tk().withdraw()

def OpenFile():
    fileName = askopenfilename(initialdir="C:/Users", filetypes = (("Text File", "*.txt"),("All Files","*.*")), title = "Open a document.")
    with open(fileName, 'r') as f:
        textFile = f.read()
        return textFile # RETURN THE FILE CONTENT HERE SO IT IS VISIBLE TO THE MAIN FUNCTION

textFile = OpenFile() # GET YOUR OUTPUT HERE SO YOU CAN PRINT IT ON THE NEXT LINE
print(textFile)