簡體   English   中英

使用python中的petl包將數據從python導出到文本文件

[英]Exporting data from python to text file using petl package in python

我試圖從文本文件中提取原始數據,並且在處理原始數據之后,我想將其導出到另一個文本文件。 以下是我為此過程編寫的python代碼。 我為此使用python 3中的“ petl”包。 “ locations.txt”是原始數據文件。

import glob, os
from petl import *


class ETL():

    def __init__(self, input):
        self.list = input


    def parse_P(self):
        personids = None
        for term in self.list:
            if term.startswith('P'):
                personids = term[1:]
        personid = personids.split(',')

        return personid

    def return_location(self):
        location = None
        for term in self.list:
            if term.startswith('L'):
                location = term[1:]
        return location

    def return_location_id(self, location):
        location = self.return_location()
        locationid = None


    def return_country_id(self):
        countryid = None
        for term in self.list:
            if term.startswith('C'):
                countryid = term[1:]

        return countryid

    def return_region_id(self):
        regionid = None
        for term in self.list:
            if term.startswith('R'):
                regionid = term[1:]

        return regionid

    def return_city_id(self):
        cityid = None
        for term in self.list:
            if term.startswith('I'):
                cityid = term[1:]
        return cityid

print (os.getcwd())
os.chdir("D:\ETL-IntroductionProject")
print (os.getcwd())
final_location = [['L','P', 'C', 'R', 'I']]

new_location = fromtext('locations.txt', encoding= 'Latin-1')
stored_list = [] 
for identifier in new_location:
    if identifier[0].startswith('L'):
        identifier = identifier[0]
        info_list = identifier.split('_')
        stored_list.append(info_list)

for lst in stored_list:
    tabling = ETL(lst)
    location = tabling.return_location()
    country = tabling.return_country_id()
    city = tabling.return_city_id()
    region = tabling.return_region_id()
    person_list = tabling.parse_P()
    for person in person_list:
        table_new = [location, person, country, region, city]
        final_location.append(table_new)

totext(final_location, 'l1.txt')

但是,當我使用petl的“ totext”功能時,會拋出“斷言錯誤”。

AssertionError:需要模板,我無法理解故障所在。 有人可以解釋一下我面臨的問題以及我應該怎么做嗎?

toext函數的template參數不是可選的,在這種情況下,沒有默認的行寫格式,必須提供一個模板。 在此處檢查toext的文檔以獲取示例: https ://petl.readthedocs.io/en/latest/io.html#text-files

模板使用字段標題來描述它寫出的每一行的格式,以描述事物,您也可以選擇傳入序言以編寫標題。 您的情況下的基本模板是:

table_new_template = "{L} {P} {C} {R} {I}" totext(final_location, 'l1.txt', template=table_new_template)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM