Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Files, Modules and Packag...
  5. Files
  6. File Operations
  7. Writing files

Writing files

File Write

  • write( ) method is used to write a string to an opened file
  • String may include numbers, special characters or other symbols.
  • If the file is opened in “w” mode all the data present in the file will be overwritten
  • Methods to write the data to a file

write

write( ) method is used to write a string to an already opened file

Syntax

fileobj.write(string)
The string that is passed as an argument to the write( ) is written into the opened file

Example

file1 = open("myfile2.txt", "w")
str1 = "It is good to learn python!!!"
file1.write(str1)
file1.close()
print("Data written successfully")

Output

writelines

writelines( ) method is used to write a list of strings

Syntax

fileobj.writelines(list_obj)

Example

file1=open("myfile3.txt",'w')
list1 = ["python\n","physics\n","chemistry\n"]
file1.writelines(list1)
file1.close()
print("Data written successfully")

Output

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments