2016-10-04 4 views
0

私は、forループを次ていますpandasとcsvモジュールを含むPythonのforループの後に文字列出力をどのように保存しますか?

for titles in titles: 
     title = titles.xpath("a/text()").extract() 
     link = titles.xpath("a/@href").extract() 
     print(title, link) 

私はformmated .csvファイルにタイトルとリンクをダンプするにはどうすればよいですか?

+0

このうち、よくハッシュ化された問題、あなたができることあなたがそれを入力したのとほぼ同じくらいGoogle。 –

+0

私はnumpyとpandasでもいくつか試しました... –

答えて

3

あなたのpython CSVモジュールを使用する必要があります。詳細はこちらWriting List of Strings to Excel CSV File in Pythonをご覧ください。このような

import csv 
results = [] 

# your code... also add this to your for loop. 
    results.append([title, link]) 

csv_file = open("csv_file.csv",'wb') 
wr = csv.writer(csv_file) 
for row in results: 
    wr.writerow(row) 
+0

助けてくれてありがとうpreston!...このアプローチを試したところ、csvファイルは空白です。次の例外があります: 'File '/ Users/user (行) TypeError: 'str'ではなくバイトのようなオブジェクトが必要です –

+2

'' wb''を 'なぜあなたがバイナリモードで開いたのか分かりません。 –

+2

あなたはどちらかを使用することができます。 –

1

csv writerを使用してください。

基本的な使用法:

import csv 
with open('file.csv') as f: 
    writer = csv.writer(f) 
    writer.writerow(["title", "link"]) 
2

サムシング(documentation):ここで

は、あなたの問題の一例である私はかなり確信している

... 
doc_path = "path/to/doc.csv" # must exist, first folder on the place 
          # where you are running the script! 
with open(doc_path, 'a') as doc: 
    for entry in titles: 
     title = entry.xpath("a/text()").extract() 
     link = entry.xpath("a/@href").extract() 
     print(title, link) 
     doc.write(str(title)+','+str(link)+'\n') 
+1

ありがとうberna!...パンダとは何か? –

+1

あなたは['pandas.DataFrame.to_csv'](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html)のようなものを使うことができますが、パンダを使っている人でも伝統的な'write'([example](http://stackoverflow.com/questions/15017072/pandas-read-csv-and-filter-columns-with-usecols))。 – berna1111

1
result = [] 
for titles in titles: 
    title = titles.xpath("a/text()").extract() 
    link = titles.xpath("a/@href").extract() 
    print(title, link) 
    result += [title + ',' + link + '\n'] 

with open("result.csv" "w+") as f: 
    f.writelines(result) 
+1

ありがとう!...この例外があります: '行24、解析中 結果+ = [タイトル+ '、' +リンク+ '\ n'] TypeError:リスト(" str "ではなく)を連結してリストにのみできます' –

関連する問題