Jump to content

Programming Fundamentals/Files/Python3

From Wikiversity

files.py

[edit | edit source]
# This program 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.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikibooks.org/wiki/Python_Programming

import os

def create_file(filename):
    file = open(filename, "w")
    file.write("C\tF\n")
    for c in range(0, 51):
        f = c * 9 / 5 + 32
        file.write(f"{c:.1f}\t{f:.1f}\n")
    file.close()
    
def read_file(filename):
    file = open(filename, "r")
    for line in file:
        line = line.strip()
        print(line)
    file.close()
    print("")
    
def append_file(filename):
    file = open(filename, "a")
    for c in range(51, 101):
        f = c * 9 / 5 + 32
        file.write(f"{c:.1f}\t{f:.1f}\n")
    file.close()
    
def delete_file(filename):
    os.remove(filename)

def main():
    filename = "~file.txt"

    if os.path.isfile(filename):
        print("File already exists.")
    else:
        create_file(filename)
        read_file(filename)
        append_file(filename)
        read_file(filename)
        delete_file(filename)
        
main()

Try It

[edit | edit source]

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 | edit source]