【问题标题】:I need to get the text from uma file and put into another empty file我需要从 uma 文件中获取文本并放入另一个空文件
【发布时间】:2019-12-09 17:21:00
【问题描述】:

这是我到现在为止的代码,我需要帮助来解决这个问题,我正在尝试从一个文件中获取文本并将其放入另一个文件中,但我没有找到正确执行此操作的方法。 当我运行这段代码时,我的文件是空的。

f = open('teste.txt','r')
texto = f.readlines()

x = 0

while x < len(texto):
    if texto[x] == "\n":
        local = texto.index(texto[x])
        texto.pop(local)
    else:
        texto[x] = texto[x].split(',')
        x += 1
    # print(texto[1])


texto1 = open('gravando.txt','r+')
#   texto1.write(texto[1,5,6,7,8])
(texto1.write(line) for line in (texto[i] for i in [1,5,6,7,8]))

print('O conteudo do texto1 e ', texto1.readlines())

这是文件 teste.txt 中的文本

名称:计算资源 命名空间:投票应用程序 范围:未终止 * 匹配所有没有活动截止日期的 pod。这些 pod 通常包括长时间运行的 pod,其容器命令预计不会终止。 资源使用困难 -------- ---- ---- 限制.cpu 4 4 limits.memory 2Gi 2Gi

这是我预期的结果

命名空间:voting-application 资源使用困难 -------- ---- ---- 限制.cpu 4 4 limits.memory 2Gi 2Gi

【问题讨论】:

  • 好吧,对于初学者来说,(texto1.write(line) for line in (texto[i] for i in [1,5,6,7,8])) 正在创建生成器,那里的循环不会在您的代码中执行。您的输入文件是什么,预期的输出是什么?您可以编辑您的问题并将数据放在那里吗?
  • 我会把文本放在这里,但想法只是获取第一个文件的部分文本并将其写入第二个文件

标签: python-3.x string text


【解决方案1】:

据我了解,您正试图通过省略一些行(例如新行)来将一个文本从文件复制到另一个文本。此外,仅尝试仅编写某些行,例如 1,5,6

以下是写入另一个文件时的更正,


f = open('teste.txt','r')
texto = f.readlines()

x = 0

while x < len(texto):
    if texto[x] == "\n":
        local = texto.index(texto[x])
        texto.pop(local)
    else:        
        x += 1
    # print(texto[1])
texto1 = open('gravando.txt','r+')
[texto1.write(texto[i]) for i in [1,5,6,7,8]]

或者你可以这样做,

for i in [1,5,6,7,8]:
    texto1.write(texto[i]) 

我建议应该使用上下文管理器执行文件处理操作,

with open("test.txt", "w") as f:    
    [f.write(texto[i]) for i in [1,5,6,7,8]]

【讨论】:

  • 我收到一个错误,它不允许将列表放在那里文件“c:\Users\Eric Vitta\Documents\python\openshift\parseQuota.py”,第 20 行,在 [texto1.write(texto[i]) for i in [1,5,6,7,8]] TypeError: write() argument must be str, not list
  • 你为什么要分割逗号?拆分后只需要选定的部分吗?
  • 只有在第一个条件不成立时才会发生这种情况
  • 是的。为什么用逗号分隔行?因此,如果您不想直接分配而不拆分,或者简单地删除它。你想在最终输出中使用逗号吗?
  • 如果您只想删除 ,您可以将最后一行更新为[texto1.write("".join(texto[i])) for i in [1,5,6,7,8]]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-12
  • 2018-02-24
  • 1970-01-01
  • 2021-01-23
  • 2016-04-16
  • 2016-08-14
  • 1970-01-01
相关资源
最近更新 更多