To create a new file, or to overwrite existing one, use "w" as second argument:
f = open("external.txt", "w")
f.write("Line One")
f.write("Second One")
f.write("Third One")
f.close()
Result:
Line OneSecond OneThird One
To evade concatenation, add "\n" at the end of every new line:
f = open("external.txt", "w")
f.write("Line One \n")
f.write("Second One \n")
f.write("Third One \n")
f.close()
Result:
Line One
Second One
Third One
If you need to add new content, without destruction of previous lines, use "a" as second argument:
f = open("external_2.txt", "a")
f.write("One More Time \n")
f.write("One More Time \n")
f.write("One More Time \n")
f.close()
Content of external_2.txt after we run code from above two times:
One More Time
One More Time
One More Time
One More Time
One More Time
One More Time
Sometimes we will need to delete files and folders. About that, in next tutorial.
No comments:
Post a Comment