【问题标题】:How to read in a file and strip the lines, then split the values?如何读入文件并剥离行,然后拆分值?
【发布时间】:2023-03-25 12:16:01
【问题描述】:

我需要读入一个文件,然后剥离文件的行,然后拆分每一行的值,最后写入一个新文件。本质上,当我拆分行时,所有值都将是字符串,然后一旦它们被拆分,每行将是它自己的列表!我写的代码仍然只是复制文本并将其粘贴到新文件中,没有剥离或拆分值!

with open(data_file) as data:
    next(data)
    for line in data:
        line.rstrip
        line.split
        output.write(line)
logging.info("Successfully added lines")

【问题讨论】:

  • 要调用函数,需要在函数后面加上()。它必须是 line.rstrip()line.split()。另外,您能否添加一小部分示例输入和您期望的输出?

标签: python-3.x split strip


【解决方案1】:
with open(data_file) as data:
    next(data) #Are you sure you want this?  It essentially throws away the first line
               # of the data file
    for line in data:
        line = line.strip()
        line = line.split()
        output.write(line)
logging.info("Successfully added lines")

【讨论】:

  • 是的,我正在将一个新标题放入新文件中!谢谢你成功了!
  • line = line.strip().split() 也可以用来让它更短一点。事实上,for 循环中只需要一行:output.write(line.strip().split())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多