python-3.x 如何从写入的文件中读取?

bqf10yzr  于 2022-12-05  发布在  Python
关注(0)|答案(1)|浏览(228)

我需要在一个名为lines的函数中使用更改后的文本文档(来自函数changed_document),但我不能简单地使用更改后的列表或字符串。它显示了一个错误“AttributeError:'str'对象没有属性'readlines'"。所以我试着将更改后的文本写入一个新的文本文件,然后读取它以在line函数中使用。但是它不起作用。我无法读取新写入的文本文件。它只打印空行。

def reading():
    doc = open("C:/Users/s.txt", "r", encoding= 'utf-8')
    docu = doc
    return docu
def longest_word_place(document):
    words = document.read().split()
    i = 0
    max = 0
    max_place = 0
    for i in range(len(words)):
        if len(words[i]) > max:                                 
            max = len(words[i])
            max_place = i
    return max_place
def changed_document (document):
    list = []
    for line in document:
        for symbol in line:
            if symbol.isnumeric():
                symbol = ' '
            if symbol in "#,.;«\³][:¡|>^' '<?+=_-)(*&^%$£!`":
                symbol = ' '
            list.append(symbol)
            document_changed =''.join([str(item) for item in list])
    return document_changed

def lines(document):
    lines = document.readlines()
    max_word = ''
    max_line = 0
    for line_index, every_line in enumerate(lines, 1):
        line_words = every_line.strip().split()
        for each_word in line_words:
            if len(each_word) > len(max_word):
                max_word = each_word
                max_line = line_index
    print(f"{max_word = }, {max_line = }")
document = reading()
ch_dok = changed_document(document)

text_file = open("C:/Users/changed_doc.txt", "w+", encoding= 'utf-8')
text_file.write(ch_dok)
text_file.close

doc1 = open("C:/Users/changed_doc.txt", "r", encoding= 'utf-8')
for line1 in doc1:
   print(line1)
vx6bjr1n

vx6bjr1n1#

在“text_file.close”中,您错过了括号,因此文件没有关闭(只返回函数本身,而不是调用)。

相关问题