英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论