9-4. Creating a New File in Python

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():
    try:
        print("Creating a file of usernames from a file of names.")

        # Get the file names
        infileName = input("What file are the names in? ")
        outfileName = input("What file should the usernames go in? ")

        # Open the files
        infile = open(infileName, 'r')
        outfile = open(outfileName, 'w')

        # Process each line of the input file
        for line in infile:
            # Get the first and last names from line
            first, last = line.split()
            # Create a username using slicing
            uname = (first[0] + last[:7]).lower()

            # Write it to the output file

            print(uname, file=outfile)

        # Close both files
        infile.close()
        outfile.close()
        print("Usernames have been written to", outfileName)

    except IOError as e:
        print(f"An error occurred: {e}")

if __name__=="__main__":
    main()