Writing to an text file using Python

Configurare noua (How To)

Situatie

There are two ways to write in a file:

  1. write() : Inserts the string str1 in a single line in the text file.File_object.write(str1)
  2. 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

Tip solutie

Permanent

Voteaza

(1 din 7 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?