在Python中创建固定宽度文件

huangapple go评论64阅读模式
英文:

create Fixed Width File in Python

问题

以下是您要翻译的代码部分:

# 下面的代码创建一行字符串。我的问题是我有一个大型数据库,我需要从中创建一个固定宽度的文本文件。该文件应包含多行。

# 以下示例代码仅发布一行。

class FixWidthFieldLine(object):

    fields = (('foo', 10),
              ('bar', 30),
              ('ooga', 30),
              ('booga', 10))

    def __init__(self):
        self.foo = ''
        self.bar = ''
        self.ooga = ''
        self.booga = ''

    def __str__(self):
        return ''.join([getattr(self, field_name).ljust(width) 
                    for field_name, width in self.fields])

f = FixWidthFieldLine()
f.foo = 'hi'
f.bar = 'joe'
f.ooga = 'howya'
f.booga = 'doin?'

print f

这是代码的翻译部分,没有其他内容。

英文:

The code below creates one line of string. My problem is i have a big database. From which i have to create a fixed width text file. Which should post multiple lines

And below code example only posts one line.

can anyone help with code that post multiple line in a flatfile

class FixWidthFieldLine(object):

    fields = (('foo', 10),
              ('bar', 30),
              ('ooga', 30),
             ('booga', 10))

    def __init__(self):
        self.foo = ''
        self.bar = ''
        self.ooga = ''
        self.booga = ''

    def __str__(self):
        return ''.join([getattr(self, field_name).ljust(width) 
                    for field_name, width in self.fields])

f = FixWidthFieldLine()
f.foo = 'hi'
f.bar = 'joe'
f.ooga = 'howya'
f.booga = 'doin?'

print f

答案1

得分: 0

你可以在你的任务中使用格式化,例如.format的方式,比如你想要有宽度分别为10、15、10,那么你可以这样做:

data = (('Able', 'Baker', 'Charlie'), ('Dog', 'Easy', 'Fox'), ('George', 'How', 'Item'))
for row in data:
    print('{:10}{:15}{:10}'.format(*row))

输出结果如下:

Able      Baker          Charlie   
Dog       Easy           Fox       
George    How            Item
英文:

You might use formatting e.g. .format for your task following way, say you want to have widths 10, 15, 10 then you might do

data = (('Able','Baker','Charlie'),('Dog','Easy','Fox'),('George','How','Item'))
for row in data:
    print('{:10}{:15}{:10}'.format(*row))

gives output

Able      Baker          Charlie   
Dog       Easy           Fox       
George    How            Item      

huangapple
  • 本文由 发表于 2023年2月23日 23:36:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547013.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定