1

我正在编写一个新的 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")
4

1 回答 1

1

words从 i.split() 创建并没有对它做任何事情。从那里很难说你的思想去了哪里,但当我自欺欺人时,这就是我的代码的样子。我会这样处理:

leftmargin = leftmargin - 1 # we will add a space before the first word of each line

outline = " " * leftmargin  # line to write
for inline in file:
    for word in inline.split():
        if len(outline) + len(word) + rightmargin > max:
            # line would be too long, so write what we have and reset the outline variable
            outfile.write(outline)
            outline = " " * leftmargin
        # the above flow nicely prevents the need for more if/elses
        outline += ' ' + word

这可以改进以处理 0 个左边距和比最大行长更长的单词,但我认为它现在应该能满足你。

于 2019-09-01T13:30:29.127 回答