我正在编写一个新的 Python 代码,并希望将其读取到一个文件中,然后将文件的内容重新写入另一个文件,但增加了边距。边距必须由用户输入,文本必须左对齐。
这是一个 Python 项目,3.74 版本。我已经成功编写了用于从旧文件复制文件以及创建左边距的代码,但是我很难找到一种创建右边距的好方法。此外,我需要确定何时何地需要拆分该行并转到下一个文件。词不能分开。
#ask user to input file Name
print("\n\nEnter your file's name")
#have a file name ready
file_Name = "I'm a file.txt"
#set the line length in characters
line_Size=80
#get min size
min_Size = 7
#take in user input
#make file_Name be the name input by user
file_Name=input()
#output file
#get name from user
print("Enter the name of the file you want to output to (i.e. output file)")
show = input()
#get margins from User
#set default margins first
left_Margin=0
right_Margin=0
#ask for left margin
print("\nEnter your left margin")
#get left margin
left_Margin=int(input())
#ask for right left_Margin
print("\nEnter your right margin")
#get right margin
right_Margin=int(input())
#print margins testcase
#print(left_Margin, right_Margin)
#create varible to hold the number of characters to withold from line_Size
avoid = right_Margin
num_chars = left_Margin
#open file now
with open (file_Name, "r") as f:
#get output file ready
with open(show, "w") as f1:
for i in f:
num_chars += len(i)
string_length=len(i)+left_Margin
#string_squeeze=len(i)+right_Margin
i=i.rjust(string_length)
words = i.split()
#check if num of characters is enough
if num_chars-80-avoid-5<min_Size:
print("Here is the problem")
f1.write(i)
i.split()
f1.write('\n')
f1.write(i)
else:
f1.write(i)
f1.write("\n")