How to write to a txt file in Python?

Asked

Viewed 1,372 times

-1

How to open a txt file and add the contents of some variable in it? For example, a content that leaves the print in the code below.

for passw in senha_list:
    print(passw,end='') 
  • It is important to try to understand the concept of file first. https://docs.python.org/pt-br/3/tutorial/inputoutput.html#Reading-and-writing-files In the official Python documentation you have well explained how to open, close and write to a file.

1 answer

0

To save the data to a file, just use the command open python, in it we should pass as parameter the name of the file you want to save as well as the modo how you want to open the file on file system, you can see the documentation here.

Here is an example of the use according to the past example:

with open('saida.txt','w') as f:
    for passw in senha_list:  
        f.write('{}\n'.format(passw))

In this example we are recording an element passw per line within the archive saida.txt, for this I used the string format method, for more information how the format works, follows the documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.