I want to align string and adjust spacing in a column with the correct custom format I want.
My code:
import time
seperator='|' '-'*33 '|\n'
seperator2='|' '='*33 '|\n'
end = '|' '^'*33 '|'
t=['Tuesday','July','2022','03','06']
try:
with open('time.txt','r') as f:
content = f.readlines()
except:
with open('time.txt','w') as f:
f.write('pass')
with open('time.txt','r') as f:
content = f.readlines()
if content[0] != '_________________________________\n':
with open('time.txt','w') as f:
header= '_'*33 '\n' \
'|Day |Month |Year |Hour |Minute |\n'
data = (f'|{t[0]} |{t[1]} |{t[2]}'
f'|{t[3]} |{t[4]} |\n')
f.write(header seperator data end)
elif content[0] == '_________________________________\n':
with open('time.txt','r ') as f:
saved=f.readlines()[:-1]
f.seek(0)
data = (f'|{t[0]} |{t[1]} |{t[2]}'
f'|{t[3]} |{t[4]} |\n')
f.writelines(saved [seperator2,data,end])
Output in the time.txt file(if it has been ran once):
_________________________________
|Day |Month |Year |Hour |Minute |
|---------------------------------|
|Tuesday |July |2022|03 |06 |
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^|
Output(twice)(showing this to clarify that the data should be saved and re-printed):
_________________________________
|Day |Month |Year |Hour |Minute |
|---------------------------------|
|Tuesday |July |2022|03 |06 |
|=================================|
|Tuesday |July |2022|03 |06 |
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^|
The output I want:
_____________________________________
|Day |Month |Year |Hour |Minute |
|--------|------|-----|-----|-------|
|Tuesday |July |2022 |03 |06 |
|========|======|=====|=====|=======|
|Tuesday |July |2022 |03 |06 |
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^|
Any help would be appreciated, Thanks.
CodePudding user response:
The following code can be consulted, the logic and procedure are commented, if the task is not limited to something specific like here, it is better to write it more modularly
PS: The logic of length and length_total can be rewritten to adjust the spacing between characters
import os
def align_column(items, length):
res = []
for index, item in enumerate(items):
item_length = len(item)
# Determine if the length reaches the maximum length of this column, or if not, add spaces
if item_length < length[index]:
res.append(item " " * (length[index] - item_length))
else:
res.append(item)
# Add the | character to the beginning and end
return "|" "|".join(res) "|"
def has_data(file, res=True):
if not os.path.exists(file):
res = False
else:
with open(file) as f:
if not f.read():
res = False
return res
def solution(file_name="data.txt"):
header = ['Day', 'Month', 'Year', 'Hour', 'Minute']
init_data = ['Tuesday', 'July', '2022', '03', '06']
length = [len(max(item, key=len)) for item in zip(header, init_data)] # Get the longest length of each column
length_total = sum(length) len(length) 1 # Get the length of all content plus the length of the character|
if not has_data(file_name): # File does not exist or content is empty
contents = ["-" * length_total]
# Add content to the list in sequence for easy one-off addition
contents.append(align_column(header, length))
contents.append("|" "-" * (length_total - 2) "|")
contents.append(align_column(init_data, length))
contents.append("|" "^" * (length_total - 2) "|")
with open(file_name, "w") as f:
f.write("\n".join(contents))
else:
with open(file_name) as f:
# If there is content, remove the ^ character from the last line
contents = f.readlines()[:-1]
# Add content to the list in sequence for easy one-off addition
# The previous implementation already contained the newline character \n at the end, so the last character needs to be unified
contents.append("|" "=" * (length_total - 2) "|\n")
contents.append(align_column(init_data, length) "\n")
contents.append("|" "^" * (length_total - 2) "|\n")
with open(file_name, "w") as f2:
f2.write("".join(contents))
solution()
OUTPUT:
# first time
--------------------------------
|Day |Month|Year|Hour|Minute|
|------------------------------|
|Tuesday|July |2022|03 |06 |
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^|
# second time
--------------------------------
|Day |Month|Year|Hour|Minute|
|------------------------------|
|Tuesday|July |2022|03 |06 |
|==============================|
|Tuesday|July |2022|03 |06 |
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^|
# third time
--------------------------------
|Day |Month|Year|Hour|Minute|
|------------------------------|
|Tuesday|July |2022|03 |06 |
|==============================|
|Tuesday|July |2022|03 |06 |
|==============================|
|Tuesday|July |2022|03 |06 |
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^|