In Python, you can create a new file using the open() function with specific modes. Here’s how you can do it with different modes:
- Create Mode ("x"): Creates a new file and returns an error if the file already exists.
- Append Mode ("a"): Opens a file for appending and creates the file if it does not exist.
- Write Mode ("w"): Opens a file for writing and creates the file if it does not exist.
Example: Creating a File Using Write Mode
To create a file using the write mode, which will create the file if it does not exist:
def main(): # Open a file for writing (creates if it does not exist) with open("newfile_write.txt", "w") as f: f.write("This file is created and written to in write mode.\n") # Verify the file content with open("newfile_write.txt", "r") as f: print(f.read()) if __name__=="__main__": main() |
Explanation:
- Open the File in Write Mode: Use open("newfile_write.txt", "w") to open the file for writing. This will create the file if it does not exist.
- Write to the File: Use write() to add content to the file.
- Close the File: Always close the file after performing operations on it.
- Read the File: Reopen the file in read mode to verify its content.
This code example demonstrates creating a file of usernames from a file that contains names.
def main(): print(uname, file=outfile) |