簡體   English   中英

Python程序讀取一個文本文件,然后將其內容寫入另一個文件,不同大小的邊距,由用戶輸入

[英]Python Program to Read in a File of Text and then Write its Contents in Another File, with Margins of Different Sizes, Input By User

我正在編寫一個新的 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")

您從 i.split() 創建了words ,但什么也沒做。 從那里很難說你的想法去了哪里,但這就是我自欺欺人時我的代碼的樣子。 我會這樣處理:

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 個 leftmargins 和比最大行長更長的單詞,但我認為它現在應該可以容納你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM