【问题标题】:python file iteration to change the formatting of output (going from a column to line)python文件迭代以更改输出格式(从列到行)
【发布时间】:2016-04-22 18:26:21
【问题描述】:

文本文件:

a
b
c
d
e

想要的输出:

a,b,c,d,e 

这是我目前所拥有的:

#!/usr/bin/env python
import csv

list=[]
file= open('file.txt') 

for line in file:
    k=line.strip()
    list.append(k)
    print list

输出是['a', 'b', 'c', 'd']

【问题讨论】:

  • 不是python,而是tr '\n' ',' 会完成这项工作...

标签: python list for-loop iteration


【解决方案1】:

这样的?

print ','.join(open('file.txt').read().splitlines())

或者,如果它要成为更大代码库的一部分:

with open('file.txt') as fp:
    print ','.join(fp.read().splitlines())

(它会自动为你关闭文件句柄)。

分成一口大小的块:

with open('file.txt') as fp:
    text = fp.read()           # read the entire file content into `text`
lines = text.splitlines()      # split the text into a list of lines
output = ','.join(lines)       # use comma to join the lines into a string
print output                   # and print it.

【讨论】:

  • 你能写出整个脚本吗,这样我可以更好地理解它并为自己学习它@thebjorn?
  • 这是整个脚本..运行它你会看到:-)
  • 这里只是挑剔,但您可以通过添加with 语句来自动打开和关闭文件来稍微改进一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
  • 1970-01-01
  • 2018-10-25
  • 2019-06-13
  • 1970-01-01
  • 2022-06-16
相关资源
最近更新 更多