Situatie
There are two ways to write in a file:
- write() : Inserts the string str1 in a single line in the text file.File_object.write(str1)
- writelines() : For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.File_object.writelines(L) for L = [str1, str2, str3]
Solutie
Pasi de urmat
# Python program to demonstrate
# writing to file
# Opening a file
file1 = open(‘myfile.txt’, ‘w’)
L = [“Test 2 \n”, “Test 3 \n”, “Test 4 \n”]
s = “Test\n”
# Writing a string to file
file1.write(s)
# Writing multiple strings
# at a time
file1.writelines(L)
# Closing file
file1.close()
# Checking if the data is
# written to file or not
file1 = open(‘myfile.txt’, ‘r’)
print(file1.read())
file1.close()
Output:
Test
Test 2
Test 3
Test 4
Leave A Comment?