Python Write To File Line By Line
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
numbers = ["One\n", "Two\n", "Three\n", "Four\n", "Five\n"] F = open("devops.txt", "a") F.writelines(numbers) F.close()
Output:
devops.txt
One Two Three Four Five
Python Write To File Line By Line Using writelines() and For Loop:
lines = ['line1', 'line2',"line3"] f=open('devops.txt', 'a') f.writelines("%s\n" % i for i in lines) f.close()
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
line1 line2 line3
or Opening a File In a Different Way:
lines = ['line1', 'line2'] with open('devops.txt', 'a') as f: f.writelines("%s\n" % l for l in lines)
here we used the same code as above but to open the file and append we used a different method.
Output:
devops.txt
line1 line2
Python Write To File Line By Line Using write() and For Loop:
abc = ["One", "Two", "Three", "Four", "Five"] x = open("devops.txt", "a") for i in abc: x.write('\n%s' % i) x.close()
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
One Two Three Four Five
Read a file line by line and write this lines into new file
with open("devops.txt","r") as d: x=d.readlines() with open("new.txt","w") as f: f.writelines(x) f.close()
above code will read the devops.txt file line by line and write intoto another file called new.txt. So the both files will be look similar.