2016-02-28 33 views
0

我有一個文本文件,它有很多行。我想提取某些行並將它們寫入CSV文件。但是,我想將特定的行寫入CSV文件中的同一行。例如,我的文本文件是這樣的:Python:寫入CSV文件中的相同行

Name= Sarah F 
Location= Baltimore MD 
Name= Bob M 
Location= Sacramento CA 
Name= Tom M NY 
Location= Brooklyn NY 
Name= Anne F 
Location= Morristown NJ 

我的CSV文件,我想生成將包括人,他們居住在姓名,性別,城市和國家:

Sarah,F,Baltimore,MD 
Bob,M,Sacramento,CA 
Tom,M,Brooklyn,NY 
Anne,F,Morristown,NJ 

當我使用csv.writerows([list])我得到的namessexcitystate寫在不同的行:

Sarah,F 
Baltimore,MD 
Bob,M 
Sacramento,CA 
Tom,M 
Brooklyn,NY 
Anne,F 
Morristown,NJ 

當我嘗試追加到列表中時:[name, sex]citystate覆蓋原始列表而不是追加。

這裏是我的代碼來做到這一點:

import csv 

file = open("file_to_use.txt", 'r') 
csv_file = open("file_to_write.csv", 'wb') 
writer = csv.writer(csv_file) 

Row_lines =[] 

for line in file: 

    if line.startswith("Name="): 
     name_line = line.replace(" ", ",") 
     name_line = name_line.strip("\n") 

     Row_lines.append(name_line) 

    if line.startswith("Location="): 
     loc_line = line.replace(" ", ",") 
     loc_line = loc_line.strip("\n")     

     Row_lines.append(loc_line) 

    writer.writerows(Row_lines) 

csv_file.close() 

我知道我有不正確的地方一定的邏輯順序,但我似乎無法弄清楚。

+0

'Name ='和'Location ='行總是在輸入文件中交替出現?輸入文件中是否還有其他行或只有這兩種類型? –

回答

0

每次調用Row_lines.append()時,都會將新項目添加到列表中。當您調用writer.writerows(Row_lines)時,列表中的每個項目都會作爲單獨的行寫入。

每次遇到名稱行時,都應該從該行創建一個新字符串,但不要將其添加到Row_lines列表中。每次遇到位置線時,都應該將其附加到名稱行字符串,創建一個完整的行,您現在可以將其添加到Row_lines列表中。

而不是在循環的每次迭代中調用writerows(),您應該在編譯完整行的列表後調用它。

import csv 

file = open("file_to_use.txt", 'r') 
csv_file = open("file_to_write.csv", 'wb') 
writer = csv.writer(csv_file) 

Row_lines =[] 

for line in file: 

    if line.startswith("Name="): 
     name_line = line.replace(" ", ",") 
     name_line = name_line.strip("\n") 

     # start building the new line 
     current_line = name_line 

    if line.startswith("Location="): 
     loc_line = line.replace(" ", ",") 
     loc_line = loc_line.strip("\n")     

     # append the extra fields to the current line 
     current_line = current_line + ',' + loc_line 

     # add the current line to the output list 
     Row_lines.append(current_line) 

# call this after you have added 
# all lines, not after each one 
writer.writerows(Row_lines) 

csv_file.close() 
0

要將兩個不同行Row_lines表示一個單一csv行,你應該只添加一個行Row_lines每一行。

0

你的任務有兩部分。首先是加盟行,你可以使用zip爲:

with open(inputfile) as propsfile: 
    data = [row.split("=")[1].split() for row in propsfile] 

# join two at a time 
data_tuples = zip(data[::2], data[1::2]) 

二是寫作的行,您可以使用該csv模塊:

import csv 
with open(outputfile, 'w') as csvfile: 
    writer = csv.writer(csvfile) 
    writer.writerows([name+location for name, location in data_tuples]) 

現在我們有數據outputfile

Sarah,F,Baltimore,MD 
Bob,M,Sacramento,CA 
... 
0

這是一個不使用任何外部庫的代碼。因爲你所有的行不一定是一致的(例如「Name = Tom M NY」--NY應該不在那裏),這段代碼查看「Name =」或「Location =」後面的兩個第一個數據條目,忽略任何後續條目(如上例中的「NY」)。

# Opening the file to use 
input_file = open(r"C:\Temp\file_to_use.txt", 'r') 

# Creating an empty CSV file 
output_file = open(r"C:\Temp\output.csv", 'w') 

# Going through the text file, it is checking whether the line holds name or location information 
# If it holds location information, all saved information so far is saved to the CSV file 
for line in input_file: 
    line = line.split("=") 
    if line[0] == "Name": 
     first_name, last_name = line[1].strip().split()[:2] 
    elif line[0] == "Location": 
     city, state = line[1].strip().split()[:2] 
     output_file.write('%s,%s,%s,%s\n' % (first_name, last_name, city, state)) 

# Closes the opened files 
input_file.close() 
output_file.close()