如何在一行中的不同位置添加分隔符(,)并在python 3中写入文本文件

时间:2017-09-22 20:41:21

标签: python python-3.x

这是我的示例输入文件数据

  

0067011990999991950051507004 + 68750 + 023550FM-12 + + 038299999V0203301N00671220001CN9999999N9 00001 + 99999999999

     

0043011990999991950051512004 + 68750 + 023550FM-12 + + 038299999V0203201N00671220001CN9999999N9 + 00221 99999999999

我正在尝试在一行中划分特定长度以保存在db表中的各个列中。以下是示例输出。

  

0067,011990,99999,19500515,0700,4,+ 68750,+ 023550,FM-12,+ 0382,99999,V020,330,1,N,0067,1,2,20001,C,N, 999999,9,N,9,+ 0000,1,+ 9999,9,99999,9

代码

with open('data1.txt', 'w', encoding='latin_1') as output:
    with open('data.txt', 'r', encoding='latin_1') as input:
        for line in input:
            nline = line+','
            output.write(nline)

任何建议都会有所帮助。

3 个答案:

答案 0 :(得分:1)

如果这是固定宽度分隔的,我可能会编写一个采用一系列字符宽度并在每个字符宽度之间输出逗号的生成器。虽然老实说这更多是因为它显然正确而非效率。

def add_commas(s, widths):
    ss = iter(s)
    for w in widths:
        for _ in range(w):
            try:
                yield next(ss)
            except StopIteration:
                return
        yield ","
    yield from ss

''.join(add_commas("this is really long", [4, 3, 5]))
# 'this, is, real,ly long'

如果您愿意,请将其包装在直接输出字符串的函数中

from functools import wraps

def output_str(wrapped):
    @wraps(wrapped)
    def wrapper(*args, **kwargs):
        return ''.join(wrapped(*args, **kwargs))
    return wrapper

@output_str
def add_commas(s, widths):  # as above...
    ss = iter(s)
    for w in widths:
        for _ in range(w):
            try:
                yield next(ss)
            except StopIteration:
                return
        yield ","
    yield from ss

add_commas("this is really long", [4, 3, 5])

答案 1 :(得分:0)

这个怎么样? 我们以相反的顺序插入逗号:

string = "0043011990999991950051512004+68750+023550FM-12+038299999V0203201N00671220001CN9999999N9+00221+99999999999"
lst = list(string)
delimiters = [1,7,9,10]

for item in delimiters[::-1]:
    lst.insert(item,",")

''.join(lst)

或作为一种功能

string = "0043011990999991950051512004+68750+023550FM-12+038299999V0203201N00671220001CN9999999N9+00221+99999999999"
delimiters = [1,7,9,10]

def add_delimiters(string):
    lst = list(string) 
    for item in delimiters[::-1]:
        lst.insert(item,",")
    return ''.join(lst)

add_delimiters(string)

答案 2 :(得分:-1)

import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { ActivatedRoute } from '@angular/router';
@Component({
    selector: 'browse-category',
    template: require('./browse-category.component.html'),
    styles: [require('./browse-category.component.css')]
})
export class BrowseCategoryComponent {
    products: IProduct[];
    category: ICategory;
    categoryId: number;
    constructor(private route: ActivatedRoute, private http: Http, @Inject('ORIGIN_URL') private originUrl: string) {

    }

    ngOnInit(): void {
        this.route.params.subscribe(params => {
            this.categoryId = +params['categoryId']; 
            // get category details
            this.http.get(this.originUrl + '/api/Category/' + this.categoryId).subscribe(result => {
                var data = result.json().data;
                if (data != null && result.status === 200) {
                    this.category = data;
                    console.log(this.category);
                }
            });
        });
    }
}