π Day 85/150 – File Write Operation in Python
Writing data to files is an essential skill in Python. Whether you're saving user input, creating reports, or logging application data, Python makes file writing simple and efficient. In this post, we'll explore four common methods to write data to a file.
Method 1 – Using write()
The write() method writes a string to a file. If the file doesn't exist, Python creates it automatically.
Hello, World!file = open("sample.txt", "w") file.write("Hello, World!") file.close()
Output (sample.txt)
Explanation:
- "w" opens the file in write mode.
- If the file already exists, its previous content is overwritten.
- Always close the file after writing.
Method 2 – Using the with Statement
The with statement automatically closes the file after writing, making it the recommended approach.
Welcome to Python!with open("sample.txt", "w") as file: file.write("Welcome to Python!")
Output (sample.txt)
Explanation:
- No need to call close().
- Safer and cleaner than manually opening and closing files.
Method 3 – Writing Multiple Lines with writelines()
Use writelines() to write multiple strings to a file.
lines = [ "Python\n", "Java\n", "C++\n" ] with open("sample.txt", "w") as file: file.writelines(lines)
Output (sample.txt)
PythonJava
C++
Explanation:
- writelines() writes each string in the list.
- Include \n if you want each item on a new line.
Method 4 – Taking User Input
Write user-provided text into a file.
text = input("Enter text: ") with open("sample.txt", "w") as file: file.write(text) print("Data written successfully!")
Sample Input
Learning Python is fun!Output (sample.txt)
Learning Python is fun!
Explanation:
- Accepts text from the user.
- Saves it directly into the file.
- Useful for forms, notes, and basic data storage.
Comparison of Methods
| Method | Best For |
|---|---|
| write() | Writing a single string |
| with open() | Safe and recommended file handling |
| writelines() | Writing multiple lines |
| User Input | Saving user-generated content |
π₯ Key Takeaways
- Use write() to write a single string to a file.
- Prefer with open() because it automatically closes the file.
- Use writelines() when writing multiple lines at once.
- Opening a file in "w" mode overwrites any existing content.
- File writing is widely used for logging, reports, data storage, and automation.
Stay tuned for Day 86 of the #150DaysOfPython series! π


0 Comments:
Post a Comment