2017-02-24 44 views
1

我遇到了一個複雜問題,我將盡我所能描述。將行數據複製到文本文件中的另一列描述

我有一個具有以下信息的文本文件

客戶名稱:扎克客戶編號:12345

10.4 2014556 - FSV聚-1.50 02月16日6各單位定購

10.5 2014556 - FSV保利-1.50 Feb 16 6每單元訂單

客戶名稱:Larry客戶編號:00099

1.4 2014556 - FSV聚-1.50 02月16日6各單位定購

1.5 2014556 - FSV聚-1.50 02月16日6各單位定購

客戶名稱:詹姆斯客戶編號:99999

5.4 2014556 - FSV聚-1.50 02月16日6每單位定購

5.5 2014556 - FSV聚-1.50 02月16日6每單位定購

等等.....以相同的格式。

我想要做什麼,是添加客戶名稱價值,「扎克」和客戶編號「」到行的結束和擺脫當前格式。 最終以這種新格式結束。

10.4 2014556 - FSV聚-1.50 02月16日6每單位定購扎克12345

10.5 2014556 - FSV聚-1.50 02月16日6每單位定購扎克12345

1.4 2014556 - FSV聚-1.50二月16 6每單位定購拉里00099

1.5 2014556 - FSV聚-1.50 02月16日6各單位定購拉里00099

5.4 2014556 - FSV聚-1.50 02月16日6各單位定購詹姆斯99999

5.5 2014556 - FSV保利-1.50 Feb 16 6每個單位訂單James 99999

我的想法就像......如果行以數字開頭,則將最後一位客戶姓名值和客戶號碼值添加到結尾該行?

這甚至可能嗎?

非常感謝你的時間!

這裏是我的代碼:

import re 
file = open('Orders.txt', 'r') 
for line in file: 
    if line.__contains__('Customer Name') or line[0].isdigit(): 
     print(line.lstrip()) 

這裏是數據的一個更好的例子:

enter image description here

回答

1

首先,要小心打開一個文件,你必須再到調用file.close()!

你發現你可以做的是通過文件迭代,每次改變客戶姓名和電話號碼一個

這是我的看法:

customer_number = 0 
customer_name = '' 
with open('Orders.txt', 'r') as file: # Usually it's how files are opened 
    while True: 
     line = file.readline() 
     if line == '': # We get out of the loop when we're finished 
      break 
     if 'Customer Name' in line: 
      # Change customer number and name 
      # Quite hacky way to do it 
      listline = line.split('Customer') 
      customer_name = listline[0] 
      customer_number = listline[1] 
     else : 
      print('%s, %s, %s' % (line.strip(), customer_name, customer_number)) 

注意,在該行年底將寫成'Name:yourcustomername','Number:yourcustomernumber'。 你可以很容易地得到這個名字和數字,但我會讓你找出你自己:)

我也建議你保存你的修改,而不是簡單地打印它們。

+0

感謝您的幫助!你可以通過解析它來解釋Change customer number和name嗎?另外爲什麼cuatomer_name沒有價值? – Cesar

+0

編輯我的答案是更明確。 – LoicM

+0

你真了不起!謝謝 :) – Cesar

相關問題