I am fairly new to Python and I'm trying to make a script that does three basic things: prints the contents of a file, overwrites it with your new lines, and prints the new file. I rewrote the script with functions and was looking for critiques. Is this a good use of functions? What would you do different?
print("Type the name of the file for overwriting.")
file = input(">")
x = open(file)
print("The contents are currently: \n", x.read())
print("Enter in the new lines")
l1 = input(">")
l2 = input(">")
l3 = input(">")
x.close()
y = open(file, 'w')
print("Entering new lines.")
y.write(l1 + '\n' + l2 + '\n' + l3)
y.close()
z = open(file).read()
print("The new contents are:")
print(z)
Script with functions:
def open_and_read(x):
print(open(x).read())
def nl(x):
z.write(x + '\n')
temp = ">"
print("Type the name of the file for overwriting.")
file = input(temp)
print(f"The current content of {file} is:")
open_and_read(file)
z = open(file, 'w')
print("Enter in three new lines of text:")
l1 = input(temp)
l2 = input(temp)
l3 = input(temp)
nl(l1)
nl(l2)
nl(l3)
z.close()
print("The new contents are:")
open_and_read(file)