【问题标题】:How to write every 3rd character from one file to a different file python3如何将一个文件中的每个第三个字符写入另一个文件python3
【发布时间】:2020-07-01 13:59:38
【问题描述】:

这是作业的一部分。我想用 ulaz 变量读取输入文件,并将该文件中的每个第三个字符写入输出文件。我正在考虑将第一个文件写入列表,而不是首先删除 '\n'。之后,在写入新文件时,我只能想到使用 [::3] 来获取每个第 3 个字符。目前,我仍在为输入数据而苦苦挣扎。每当我写一个列表(列表)时,我都会得到所有的行,但不是第一行。我不确定为什么会这样?

ulaz = input("Unesite ime fajla:")
# izlaz = input("Unesite ime fajla:")

with open(ulaz) as existing_file:
    lista = []
    for line in existing_file:
         lista.append([s.rstrip('n') for s in existing_file])
    print(lista)

【问题讨论】:

    标签: python-3.x file io with-statement


    【解决方案1】:

    existing_file.read() 会给你一个包含文件中所有文本的字符串。然后,您可以使用问题中提到的下标。

    ulaz = input("Unesite ime fajla:")
    
    with open(ulaz) as existing_file:
        text = existing_file.read()
        print(text[::3])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-24
      • 2020-01-25
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 2016-08-05
      • 1970-01-01
      相关资源
      最近更新 更多