Python Text to File: 60 Copy-Paste Code Snippets
These 60 ready-to-use Python snippets are for anyone who needs to write text to a file right now—whether you're logging errors, saving user input, exporting data, or just testing a script. Each line is short enough to copy, paste, and adapt in seconds, so you can get back to building.
Short and Sweet One-Liners
Perfect for quick tests or when you need a minimal solution without extra fluff.
- open('file.txt', 'w').write('Hello, world!')
- with open('data.txt', 'a') as f: f.write('New line\n')
- print('Saved!', file=open('log.txt', 'a'))
- open('output.txt', 'w').writelines(['line1\n', 'line2\n'])
- Path('file.txt').write_text('Hello from Python')
- with open('file.txt', 'w') as f: f.write('Overwrite this')
- open('notes.txt', 'x').write('Create new file')
- with open('data.txt', 'r+') as f: f.write('Start here')
Appending and Adding Lines
When you need to add to an existing file without wiping what's already there, these snippets keep your data safe.
- with open('log.txt', 'a') as f: f.write('More info\n')
- with open('list.txt', 'a') as f: f.write('item3\n')
- with open('output.txt', 'a') as f: f.writelines(['a\n', 'b\n', 'c\n'])
- with open('file.txt', 'a') as f: f.write(f'{value}\n')
- with open('history.txt', 'a') as f: f.write(str(datetime.now()) + '\n')
- with open('data.txt', 'a') as f: f.write('line' + str(i) + '\n')
- with open('log.txt', 'a') as f: f.write('Error: ' + str(e) + '\n')
- with open('results.txt', 'a') as f: f.write('Score: ' + str(score) + '\n')
Writing Multiple Lines or Lists
For when you have a list or multiple strings to write at once—clean and efficient.
- with open('file.txt', 'w') as f: f.write('\n'.join(lines))
- with open('file.txt', 'w') as f: f.writelines(line + '\n' for line in lines)
- with open('output.txt', 'w') as f: [f.write(item + '\n') for item in items]
- with open('data.txt', 'w') as f: f.write('\n'.join(map(str, numbers)))
- with open('file.txt', 'w') as f: f.write('\n'.join([f'{k}: {v}' for k, v in dict.items()]))
- with open('list.txt', 'w') as f: f.write('\n'.join(fruits))
- with open('output.txt', 'w') as f: f.write('\n'.join(str(x) for x in range(10)))
- with open('file.txt', 'w') as f: f.writelines(f'{i}\n' for i in range(1, 6))
Handling Exceptions and Errors
When you need to write error logs or ensure your file operations don't crash, these are your go-to snippets.
- try: with open('file.txt', 'w') as f: f.write(data) except: print('Failed')
- try: with open('log.txt', 'a') as f: f.write('Error: ' + str(e)) except: pass
- with open('error.log', 'a') as f: f.write(f'{datetime.now()}: {e}\n')
- try: open('file.txt', 'w').write('Safe') except IOError: print('Cannot write')
- try: with open('data.txt', 'w') as f: f.write('Important') except Exception as ex: print(ex)
- with open('debug.txt', 'a') as f: f.write(f'Line {lineno}: {message}\n')
- try: with open('out.txt', 'w') as f: f.write('Done') finally: print('Finished')
- with open('trace.txt', 'a') as f: f.write(f'At step {step}: {status}\n')
Reading and Writing with Context Managers
Best practice for clean code—these snippets ensure files are closed properly even if errors occur.
- with open('file.txt', 'w') as f: f.write('Context manager')
- with open('data.txt', 'r') as f: content = f.read(); with open('copy.txt', 'w') as out: out.write(content)
- with open('in.txt', 'r') as f, open('out.txt', 'w') as g: g.write(f.read())
- with open('file.txt', 'w') as f: f.write('Line1\nLine2\n')
- with open('file.txt', 'a') as f: f.write('Appended with with')
- with open('file.txt', 'w') as f: f.write('Safe and clean')
- with open('file.txt', 'w') as f: f.write('No need to close')
- with open('file.txt', 'w') as f: f.write('Auto-close on exit')
Writing with Encoding and Paths
For special characters or when you need to specify a file path, these snippets handle it gracefully.
- with open('file.txt', 'w', encoding='utf-8') as f: f.write('Café')
- with open('data.txt', 'w', encoding='utf-8') as f: f.write('ñ and ü')
- from pathlib import Path; Path('dir/file.txt').write_text('Hello')
- with open('/tmp/output.txt', 'w') as f: f.write('Temp file')
- with open('subfolder/file.txt', 'w') as f: f.write('Nested path')
- with open('file.txt', 'w', newline='') as f: f.write('No extra newlines')
- with open('file.txt', 'w') as f: f.write('Use raw string: r"C:\\path\\file.txt"')
- with open('file.txt', 'w') as f: f.write('Path: ' + str(Path.home() / 'file.txt'))
Practical Tips for Choosing and Personalising
Pick the snippet that matches your exact need—whether it's appending, overwriting, or handling errors. Adjust the file name, mode, and content to fit your project. For example, change 'w' to 'a' to append instead of overwrite, or add encoding='utf-8' for special characters.
Frequently Asked Questions
How do I write a string to a file in Python?
Use open('file.txt', 'w').write('your text') for a quick write, or the safer with open('file.txt', 'w') as f: f.write('your text') which auto-closes the file.
What's the difference between 'w' and 'a' modes?
'w' overwrites the file completely, while 'a' appends to the end, preserving existing content. Use 'w' when you want a fresh start, 'a' when you're adding logs or records.
How can I write multiple lines at once?
Use writelines() with a list of strings, or join them with newline characters: f.write('\n'.join(lines)).
What if I get a Unicode error when writing special characters?
Specify the encoding: open('file.txt', 'w', encoding='utf-8') to handle characters like é or 漢字.
How do I write to a file in a different directory?
Provide the full path or a relative path like 'subfolder/file.txt'. Ensure the directory exists, or create it first with os.makedirs().