Home > Software design >  Python - define a function to manage files
Python - define a function to manage files

Time:12-19

I need to define a fucntion that will, in short:

  1. Open and grab the content from an existing file
  2. Transform that content
  3. Create a new file
  4. Write that new content in this new file
  5. Print the content of the new file

I'm a complete begginer, but I got this until now. How can I improve this?

def text(): 

#open the existing file
    text_file = open('music.txt', 'r') 

#reads the file
    reading = text_file.read () 

#this turns everything to lower case, counts the words and displays the list vertically
    from collections import Counter
    new_text = reading.lower() 
    list_words = Counter(new_text.split())
    ordered_list = sorted(list_words.items())  

#creates a new file and writes the content there
    with open('finheiro_saida.txt', 'x') as final_file:
        for i in ordem:
            finheiro_saida.write(str(i)   '\n') 

#not sure how to open this new file and print its content, when I tried it says the new file doesn't exist in the directory - tried everything.

final = open('C:/Users/maria/OneDrive/Documents/SD_DTM/ficheiro_saida.txt', 'r')
read_file = final.read ()
print(read_file)

CodePudding user response:

You can open the new file and print its content the same way you read and wrote to it!

# ...After all your previous code...

with open('finheiro_saida.txt', 'r') as final_file:
    final_file_content = final_file.read()
    print(final_file_content)

CodePudding user response:

Fixed some syntax error in your code. you can display the the same way you read. Also provide all imports to the start of the file. you can also read all lines from the file as a list using file.readlines()

from collections import Counter


def text():

    # open the existing file
    text_file = open("music.txt", "r")

    # reads the file
    reading = text_file.read()

    # this turns everything to lower case, counts the words and displays the list vertically
    new_text = reading.lower()
    list_words = Counter(new_text.split())
    ordered_list = sorted(list_words.items())

    # creates a new file and writes the content there
    file_name = "finheiro_saida.txt"
    with open("finheiro_saida.txt", "x") as final_file:
        for i in ordered_list:
            final_file.write(str(i)   "\n")

    return file_name


def display(final_file_name):
    with open(final_file_name) as file:
        print(file.read())


final_file_name = text()
display(final_file_name)
  • Related