简单文本文件:
whatevera, what2
whateverb, what3
whateverc, what4
whateverd, what5
或
(whatevera, what2)
(whateverb, what3)
(whateverc, what4)
(whateverd, what5)
逐行打印。
with open('file.txt') as fp:
for line in fp:
line = line.rstrip()
print line
通过循环打印第一个元素或第二个元素的最佳方法是什么 通过使用forloop的每一行?
for line in f:
print line[0]
whatevera
whateverb
whateverc
whateverd
第二个元素
for line in f:
print line[1]
what2
what3
what4
what5
答案 0 :(得分:1)
使用zip()函数获取列:
with open('file.txt') as fp:
first, second = zip(*[line.rstrip().split(',') for line in fp])
print first
print second
由于此方法会在tuple
中打印项目,如果您想以列模式打印项目,可以使用换行符加入单词:
print '\n'.join(first)
如果您想在打印前修改线条(修改它们等),您可以简单地循环和拆分。最好从上述脚本循环遍历frist
和second
tuples
。否则,它不是一种优化和pythonic的方式来单独循环文件以访问第一和第二项。
答案 1 :(得分:0)
这可以使用python中的函数split()
来完成。使用函数将允许您重用代码。
def create_list(filename):
element_list = []
with open(filename) as f:
for line in f:
line_data = line.split(',')
'''you can change line_data[0] to line_data[1]
if you want to print the next half of the txt line'''
element_list.append(line_data[0])
return element_list
print(create_list('file.txt'))
如果需要,您可以稍后将line_data [1]附加到其他列表。