Python Write To File Line By Line:

Python Write To File Line By Line Using writelines():

Here in the first line, we defined a list in a variable called ‘numbers’. you can give any name to this variable. and we are opening the devops.txt file and appending lines to the text file. in python writelines(), module need a list of data to write. so we mentioned variable ‘numbers’ in writelines() function and in the last line we closed the opened file

Output:

devops.txt

Python Write To File Line By Line Using writelines() and For Loop:

here in the first line we defined a list with varaible lines. and in the second line, we are opening the file to append the new lines. and then by using writelines() function we are sending the list to the file line by line. writelines function in python needs a list. so here we are sending list ‘lines’ to writelines() by using for loop.

Output:

devops.txt

or Opening a File In a Different Way:

here we used the same code as above but to open the file and append we used a different method.

Output:

devops.txt

Python Write To File Line By Line Using write() and For Loop:

here in the first line, we defined our list which needs to add to our text file. and the second line we opened the file and appending data into that file. in the third and fourth line, we defined a for loop to write data into that file line by line. here you can see \n it will add a new line in the beginning only so our new appending data will add as a new line.

output:

devops.txt