Home > OS >  How to read from a written file?
How to read from a written file?

Time:12-04

I need to use changed text document (from a function changed_document) in a function called lines. But I cannot just simply use the changed list or string. It shows me an error that "AttributeError: 'str' object has no attribute 'readlines'". So I've tried to write the changed text in to a new text file and then read it to use in the line function. But it doesn't work. I cannot read that newly written text file. It prints just empty lines.

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)

CodePudding user response:

In "text_file.close" you missed the parenthesis, so the file is not closed (just the function itself is returned, not called). Perhaps this is the issue..?

  • Related