How to write a file in python?

i am having trouble figuring out how to get this code to write a file. i am using python 3.8

text = open("readfilein6.txt", "r") 


d = dict() 

for line in text:      
    line = line.strip() 

    line = line.lower() 
 
    words = line.split(" ") 

    for word in words: 
   
        if word in d: 
        
            d[word] = d[word] + 1
        else: 
        
            d[word] = 1

for key in list(d.keys()): 
    print(key, d[key]) 

this is my failed attempt at writing a file

file1= ("outputini6.txt")
with open(file1, "w") as file_object:
    file_object.write(key, d[key])

i get this error message:

file_object.write(key, d[key])
TypeError: write() takes exactly one argument (2 given)

it prints exactly what i need, but i also need it to write a file

Answer

You actually was really close:

text = open("readfilein6.txt", "r")

d = dict()

for line in text:
    line = line.strip()

    line = line.lower()

    words = line.split(" ")

    for word in words:

        if word in d:

            d[word] = d[word] + 1
        else:

            d[word] = 1
file1 = "outputini6.txt"
with open(file1, "w") as file_object:
    for key in list(d.keys()):
        print(key, d[key])
        file_object.write(f"{key} {d[key]}n")

The things i changed are the write, so to enter both key and value. i also called the write before the loop to not overide the saved data and write all at the same time.

Leave a Reply

Your email address will not be published. Required fields are marked *