Skip to content

Python, how to write to a file

To write content to a file, first you need to open it using the open() global function, which accepts 2 parameters: the file path, and the mode.

You can use a as the mode, to tell Python to open the file in append mode and add content to the file

filename = '/Users/flavio/test.txt'

file = open(filename, 'a')

#or

file = open(filename, mode='a')

Or you can use the w flag to clear the existing content:

filename = '/Users/flavio/test.txt'

file = open(filename, 'w')

#or

file = open(filename, mode='w')

Once you have the file open, you can use the write() and writelines() methods.

write() accepts a string.

writelines() accepts a list of strings:

filename = '/Users/flavio/test.txt'

file = open(filename, 'w')

file.write('This is a line\n')

file.writelines(['One\n', 'Two'])

file.close()

\n is a special character used to go to a new line

Remember to close a file after writing to it, using the file’s close() method.

β†’ Download my free Python Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about python: