writing files
Python supports writing files by default, no special modules are required. You can write a file using the .write() method with a parameter containing text data.
Before writing data to a file, call the open(filename,’w’) function where filename contains either the filename or the path to the filename. Finally, don’t forget to close the file.
Create file for writing:
The code below creates a new file (or overwrites) with the data.
# Filename to write
filename = "new.txt"
# Open the file with writing permission
myfile = open(filename, 'w')
# Write a line to the file
myfile.write('Written with Python\n')
# Close the file
myfile.close()
|
The ‘w’ flag makes Python truncate the file if it already exists. That is to say, if the file contents exists it will be replaced.
Append to file
If you simply want to add content to the file you can use the ‘a’ parameter.
# Filename to append
filename = "new.txt"
# The 'a' flag tells Python to keep the file contents
# and append (add line) at the end of the file.
myfile = open(filename, 'a')
# Add the line
myfile.write('Written with Python\n')
# Close the file
myfile.close()
|
Comments
Post a Comment