Applied Programming/Files/Python3

files.py

edit
"""This program demonstrates file processing.

It creates a file, adds data to the file, displays the file, appends more data 
to the file, displays the file, and then deletes the file.

It will not run if the file already exists.

Input:
    None

Output:
    A temporary file and file contents.

References:
    None

"""

import os
import sys

def create_file(filename):
    """Creates filename and adds temperature data to the file.

    Args:
        filename (string): Filename to create.

    Returns:
        None

    """
    with open(filename, "w") as file:
        file.write("C\tF\n")
        for c in range(0, 51):
            f = c * 9 / 5 + 32
            file.write("%.1f\t%.1f\n" % (c, f))


def read_file(filename):
    """Reads filename and displays each line.

    Args:
        filename (string): Filename to open and read.

    Returns:
        None

    """
    with open(filename, "r") as file:
        for line in file:
            line = line.strip()
            print(line)
    print("")
    

def append_file(filename):
    """Appends temperature data to filename.

    Args:
        filename (string): Filename to open and append.

    Returns:
        None

    """
    with open(filename, "a") as file:
        for c in range(51, 101):
            f = c * 9 / 5 + 32
            file.write("%.1f\t%.1f\n" % (c, f))


def delete_file(filename):
    """Deletes filename.

    Args:
        filename (string): Filename to delete.

    Returns:
        None

    """
    os.remove(filename)


def main():
    """Runs the main program logic."""

    try:
        filename = "~file.txt"

        if os.path.isfile(filename):
            print("File '%s' already exists." % filename)
            exit(1)

        create_file(filename)
        read_file(filename)
        append_file(filename)
        read_file(filename)
        delete_file(filename)
    except:
        print("Unexpected error.")
        print("Error:", sys.exc_info()[1])
        print("File: ", sys.exc_info()[2].tb_frame.f_code.co_filename) 
        print("Line: ", sys.exc_info()[2].tb_lineno)


main()

binary_file.py

edit

Binary files are usually thought of as being a sequence of bytes, which means the binary digits (bits) are grouped in eights. Binary files typically contain bytes that are intended to be interpreted as something other than text characters. Compiled computer programs are typical examples; indeed, compiled applications are sometimes referred to, particularly by programmers, as binaries. But binary files can also mean that they contain images, sounds, compressed versions of other files, etc.—in short, any type of file content whatsoever.[1]

"""This program demonstrates binary file creation

It creates a file and adds data to the file

Input: None

Output:
	upper_characters: file with the upper case english letters
	lower_characters: file with the lower case english letters

References:
	* https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions
	* https://en.wikipedia.org/wiki/Binary_file
	* https://www.youtube.com/watch?v=le0Bo3K-bks

"""

import sys
import struct


def get_file_name():
	"""Obtains user input for file name

	Input: None

	Returns:
		filename: string

	Except:
		ValueError: If filename is not a valid string

	Exit:
		filename is empty

	"""
	try:
		print('Please input the file name you would like to use. To exit, press Enter')
		filename = input()

		if type(filename) is not str:
			raise ValueError

		if filename == '':
			sys.exit(0)
		else:
			return filename
	except ValueError:
		print("File name must be a string.")
		print("ValueError: '%s' is invalid." % filename)


def append_characters(filename):
	"""Fills filename with the upper case english alphabet characters

	Input:
		filename: string

	Output: None

	Exits:
		ValueError: If filename is not a valid string
		ValueError: If filename is an empty string

	"""

	try:
		fd_out = open(filename, "wb")

		if type(filename) is not str:
			raise ValueError("File name must be a string.\nReceived %f" % filename)
		if filename == '':
			raise ValueError("File name cannot be empty.")

		id = 65
		val = id

		for i in range(26):
			entry = struct.pack('<HI', id, val)
			id += 1
			val = id

			fd_out.write(entry)
			fd_out.flush()

		fd_out.close()
	except:
		print("Unexpected error.")
		print("Error:", sys.exc_info()[1])
		print("File: ", sys.exc_info()[2].tb_frame.f_code.co_filename)
		print("Line: ", sys.exc_info()[2].tb_lineno)


def main():
	"""Runs the main program logic."""

	try:
		filename = get_file_name()
		append_characters(filename)
	except:
		print("Unexpected error.")
		print("Error:", sys.exc_info()[1])
		print("File: ", sys.exc_info()[2].tb_frame.f_code.co_filename)
		print("Line: ", sys.exc_info()[2].tb_lineno)


if __name__ == "__main__":
	main()

How to view file

edit

This command is the same for both Windows and UNIX based systems.

> hexdump -C "filename"
 
This is what the command should output using this python example file.

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own Python3 compiler / interpreter / IDE.

See Also

edit
  1. "Binary file". Wikipedia. 2018-12-30. https://en.wikipedia.org/w/index.php?title=Binary_file&oldid=876032410.