2017-10-12 109 views
-1

我有一個文件閱讀使用嵌套for循環的文本文件在python

section2 
Number of configurations:2 
Configuration1 
Number Of Pw:1 
PW1 
Frame_Type: E1 Unframed 
Line_Code: AMI 
Psn_Type:UDP/IPv4 
Pw_Type: SAToP 
Oam_Status: Enable 
Prevent_PW_Broadcast: Enable 
Multiplexing_Mode: Source 
Out_Label: 1 
In_Label: 8190 
Payload_Size_Bytes: 128 
Jitter_Buffer_Size: 10000 
VLAN Tagging:Enable 
VLAN ID:100 
VLAN PRIORITY:1 
file_name: MITOPExTx.img 
server_ip: 192.168.205.23 
software_version: 4.0(0.5) 
EndPW 
EndConfiguration 
Configuration2 
PW1 
Frame_Type: E1 Unframed 
Line_Code: AMI 
Psn_Type: MEF 
Pw_Type: SAToP 
Oam_Status: Disable 
Prevent_PW_Broadcast: Disable 
Multiplexing_Mode: Destination 
Out_Label: 16 
In_Label: 1 
Payload_Size_Bytes: 40 
Jitter_Buffer_Size: 20000 
EndPW 
EndConfiguration 

從該文件中的第一我需要讀取配置1,則下,我需要蘆葦PW1和然後下,我需要閱讀配置。我應該閱讀,直到完成配置。

做配置完成後我需要閱讀下that.Can有人配置2和PW幫我這個

+0

你嘗試過什麼嗎?請提及您的代碼或您想到的可能的解決方案。轉到docs.python.org,看看如何在Python中讀取文件。 – Shashank

+0

你自己嘗試過嗎?目前,它的內容如下:*「請爲我寫代碼」* – SiHa

+0

pw_num在範圍內(int(testcase_dict ['Number of Pw'])):#####配置所有pw \t \t Num_PW = INT(pw_num)+ 1個\t \t \t \t test_file裏面=打開( 「第%sConfigurations.txt」 %qvs_section, 'R') \t \t test_lines = test_file.readlines()\t \t \t 出口\t \t \t PW = 「PW」+ str(Num_PW) \t \t EndPW =「EndPW」 \t \t溫度=假 \t \t對於i在test_lines:\t \t \t \t \t如果測試用例== i.strip():\t \t \t \t \t \t \t \t對於i在test_lines:\t \t \t \t \t \t \t \t \t \t \t \t \t \t if PW == i。條():\t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t對於i在test_lines: \t \t \t \t \t \t \t打印我\t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t \t如果我== EndPW: \t \t \t \t \t \t \t \t休息 \t \t \t \t如果我==「EndConfiguration」: \t \t \t \t \t \t休息 –

回答

0

不知道爲什麼你需要嵌套的for循環:

test_file = open("Section{}Configurations.txt".format(qvs_section)) 
read_test_file = test_file.readlines() 
count = 1 
for line in read_test_file: 
    if line.strip() == "PW1": 
     print "Config{} Started".format(count) 
     continue 
    if line.strip() == "EndPW": 
     print "Config{} Finished".format(count) 
     count += 1 
     continue 
    print line.strip() 

或使用重新

import re 
config_file=open("Section{}Configurations.txt".format(qvs_section)) 
config_file_string=config_file.read() 
number_of_configs = int((re.findall("Number of configurations:(.*?)\n", config_file_string))[0].strip()) 
for i in range(number_of_configs): 
    print "CONFIGURATION:{}".format(i+1) 
    re_pattern="Configuration{}(.*?)EndConfiguration".format(i+1) 
    config = re.findall(re_pattern, config_file_string, re.DOTALL) 
    for line in config[0].split("\n"): 
     print "\t{}".format(line.strip()) 
+0

由於起始閱讀! –