简体   繁体   English

Python:使用'|'解析文本文件 到MySql表

[英]Python: Parse Text file with '|' to MySql table

I have a text file which has the following structure: 我有一个文本文件,具有以下结构:

341|18 Hello world|20090225230048AAnhStI|90|$0.30|10|289|2|2|2|Is that foo or 
boo bar?  18 |Is it boo foo and foo bar?|    |I beleive its foo.|396545163|foo 
& bar>foo & boo

Basically each data element is separated by | 基本上每个数据元素都由|分隔| . I am planning on using a Python script to parse this data and write it to a table. 我打算使用Python脚本来解析此数据并将其写入表中。 Based on the information I gathered from internet I can't take advantage of Python's tab separated or comma separated options to import such a file into a MySql data base. 根据我从互联网上收集的信息,我无法利用Python的制表符分隔符或逗号分隔选项将此类文件导入MySql数据库。

  • Am I wrong? 我错了吗?
  • If so, what would be the best option for doing such a thing? 如果是这样,做这样的事情的最佳选择是什么?

My idea is to create a table and extract only the element that I want to extract from the above string to store it in each column. 我的想法是创建一个表,只提取我想从上面的字符串中提取的元素,以将其存储在每一列中。 But, I also would like to know how to track what to extract. 但是,我也想知道如何跟踪要提取的内容。 Do I use a counter while I iterating over each element..? 迭代每个元素时,我是否使用计数器..?

I thought I'd ask these question before I proceed. 在我继续之前,我以为我会问这些问题。

My current intuition is to do the following: 我目前的直觉是执行以下操作:

import sys

file = open('datafile.txt')
for line in file:
    print line.strip().split('|') 

Your current code is fine. 你当前的代码没问题。 You can also use the csv.reader : 您也可以使用csv.reader

import csv
with open('datafile.txt', 'rb') as f:
    for row in csv.reader(f, delimiter='|'):
        ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM