1 def print_to_file(fname): 2 num = 1 3 #output_file=open(fname+"_OK.txt","w") 4 5 with open(fname+"_OK.txt","w") as output_file: 6 with open(fname, 'r') as input_file: 7 for line in input_file: 8 output_file.write('%03d %s' % (num, line)) 9 num = num + 1 10 11 while True: 12 fileName=input("請輸入待格式化代碼源文件名(含擴展名):") 13 #print_to_file("test.cpp") 14 print_to_file(fileName) 15 kkk=input("文件格式化輸出工作已經完成。是否需要繼續格式化其他文件?(Y/N):") 16 if kkk=='N' or kkk=='n': 17 break
這個代碼是讀取文本文件的所有內容並輸出到另一個新的文本文件,輸出時在每一行文本前面加上行號。
在把代碼復制到word文檔里面以前可以給代碼來一下這個操作。當然,前提是你准備把這個word文檔拿去打印,而不是准備給人家拿着word復制代碼的那種情況。