2017-05-09 66 views
1

我似乎是在「字典」格式文件...讀取和處理文本文件並保存到csv

文件頭如下:time,open,high,low,close,volume

下一行如下: 「t」:[1494257340],「o」:[206.7],「h」:[209.3],「l」:[204.50002],「c」:[204.90001],「v」:[49700650]} `

import csv 
    with open ('test_data.txt', 'rb') as f: 

    for line in f: 
     dict_file = eval(f.read()) 
     time = (dict_file['t']) # print (time) result [1494257340] 
     open_price = (dict_file['o']) # print (open_price) result [206.7] 
     high = (dict_file['h']) # print (high) result [209.3] 
     low = (dict_file['l']) # print (low) result [204.50002] 
     close = (dict_file['c']) # print (close) result [204.90001] 
     volume = (dict_file['v']) # print (volume) result [49700650] 

     print (time, open_price, high, low, close, value) 

# print result [1494257340] [206.7] [209.3] [204.50002] [204.90001] [49700650] 

# I need to remove the [] from the output. 

# expected result 

# 1494257340, 206.7, 209.3, 204.50002, 204.90001, 49700650 

結果我需要的是(變化時間( 「曆元日期格式」),以DD,毫米,YY

5/8/17, 206.7, 209.3, 204.50002, 204.90001, 49700650

,所以我知道我需要的csv.writer功能

+0

你有沒有嘗試過的字符串轉換爲一個字節? – Afflicted

+0

我對Python有點新,我不知道如何去觀看很多youtube視頻提示如何有時間如果你有時間 – bobbin

+1

我的意思是我不能真正幫助你,因爲你只給了我們一部分你的代碼。甚至沒有你需要幫助的寫部分。但我至少可以爲你做到這一點。 https://docs.python.org/3.3/howto/unicode.html有很多方法可以將str轉換爲字節。你可以通過這個鏈接找到它們,它非常簡單。另外我想指出的是,您應該將close =(dict__file ['c'])重命名爲其他名稱,因爲它會與f.close()衝突。任何方式去那個鏈接它應該幫助你。你可以做value =(dict_file [b'v']),但它可能不起作用。 – Afflicted

回答

0

我看到一些在您所提交的代碼問題。我建議你把你的任務分解成小塊,看看你是否可以單獨工作。那麼,你要做的是:

  1. 打開一個文件
  2. 按行讀取文件中的行
  3. eval每行獲得dict對象
  4. 從該對象
  5. 寫入獲取值這些值在(單獨的?)csv文件中

對不對?

現在做的每一個,一小步的時候

  1. 打開一個文件。

你上點有相當多:

with open('test_data.txt', 'rb') as f: 
    print(f.read()) 

# b'{"t":[1494257340],"o":[207.75],"h":[209.8],"l":[205.75],"c":[206.35],"v":[61035956]}\n' 

可以在r模式下打開的文件,而不是,它會給你一個字符串而非byte類型的對象

with open('test_data.txt', 'r') as f: 
    print(f.read()) 

# {"t":[1494257340],"o":[207.75],"h":[209.8],"l":[205.75],"c":[206.35],"v":[61035956]} 

它可能會導致一些問題,但應該工作,因爲eval可以很好地處理它(至少在python 3中)

  1. 讀取文件一行一行地
with open('test_data.txt', 'rb') as f: 
    for line in f: 
     print(line) 

# b'{"t":[1494257340],"o":[207.75],"h":[209.8],"l":[205.75],"c":[206.35],"v":[61035956]}\n' 

這裏,你不使用line變量,並試圖f.read(),而不是在你的代碼的另一個問題。這將只讀取整個文件(從第二行開始,因爲第一行已被讀取)。嘗試交換彼此等待看看會發生什麼

  • eval每行以得到dict對象
  • 同樣。這工作正常。但我會在這裏添加一些保護。如果文件中有空行或格式不正確,該怎麼辦?此外,如果該文件來自不受信任的來源,你可以成爲一個代碼注入的受害者在這裏,就像如果你的文件中的行更改爲:

    print("You've been hacked") or {"t":[1494257340],"o":[207.75],"h":[209.8],"l":[205.75],"c":[206.35],"v":[61035956]}

    with open('test_data.txt', 'rb') as f: 
        for line in f: 
         dict_file = eval(line) 
         print(dict_file) 
    
    # You've been hacked 
    # {'t': [1494257340], 'o': [207.75], 'h': [209.8], 'l': [205.75], 'c': [206.35], 'v': [61035956]} 
    

    我不知道您的確切規格,但您應該用json.loads來代替安全。

    ...


    你可以繼續你自己從那裏?

    從對象

  • 獲取值我覺得dict_file['t']不給你你所期望的價值。

    它給你什麼?

    爲什麼?

    如何解決?

  • 在CSV文件
  • 你可以寫一些隨機字符串到一個文件中寫入這些值?

    什麼樣的scv格式?你能格式化你的值嗎?

    檢查文檔csv模塊,它可以幫助你嗎?

    等等等等...


    編輯:解決方案

    # you can save the print output in a file by running: 
    # $ python convert_to_csv.py > output.cvs 
    import datetime, decimal, json, os 
    
    
    CSV_HEADER = 'time,open,high,low,close,volume' 
    
    
    with open('test_data.txt', 'rb') as f: 
    
        print(CSV_HEADER) 
    
        for line in f: 
         data = json.loads(line, parse_float=decimal.Decimal) 
         data['t'][0] = datetime.datetime.fromtimestamp(data['t'][0]) \ 
          .strftime('%#d/%#m/%y' if os.name == 'nt' else '%-d/%-m/%y') 
         print(','.join(str(data[k][0]) for k in 'tohlcv')) 
    

    運行:

    $ cat test_data.txt 
    {"t":[1494257340],"o":[207.75],"h":[209.8],"l":[205.75],"c":[206.35],"v":[61035956]} 
    {"t":[149],"o":[107.75],"h":[109.8],"l":[105.75],"c":[106.35],"v":[11035956]} 
    {"t":[1491234234],"o":[307.75],"h":[309.8],"l":[305.75],"c":[306.35],"v":[31035956]} 
    
    $ python convert_to_csv.py 
    time,open,high,low,close,volume 
    8/5/17,207.75,209.8,205.75,206.35,61035956 
    21/3/17,107.75,109.8,105.75,106.35,11035956 
    3/4/17,307.75,309.8,305.75,306.35,31035956 
    
    +0

    是什麼意思'謝謝你,我會經歷你所建議的 – bobbin

    +0

    @bobbin在我解決問題(或再次碰壁)時會ping我,我會發佈一個完整的解決方案供您檢查。我認爲如果我不馬上發佈它會對你更好。乾杯! – Igonato

    +0

    導入CSV 張開( 'test_data.txt')作爲csvfile: 讀者= csv.DictReader(csvfile) 爲行中的讀取器: 打印(行[ '時間'],行[ '開'],行['high'],row ['low'],row ['close'],row ['volume']) csvfile.close – bobbin

    相關問題