【问题标题】:How to reading .txt file and rewriting by adding space after specific position / index for each line in python如何读取.txt文件并通过在python中每一行的特定位置/索引后添加空格来重写
【发布时间】:2019-08-30 13:02:23
【问题描述】:

我想读取 .txt 文件并在每行的特定位置/索引后添加空格。请考虑以下示例以获取更多详细信息。

假设我的文件包含

12345 678 91011 12 1314

在上述文件中,第一行包含特定位置/索引 [4] 之后的空格,然后是位置/索引 [8] 之后、位置/索引 [14] 之后和位置/索引 [17] 之后

预期输出: 我希望文件中的每一行在特定位置之后都有空间。即对于第一行,我想在索引 [2] 之后添加空格,然后在索引 [6] 之后添加空格,然后在索引 [11] 之后添加空格,然后在索引 [21] 之后添加空格,依此类推...

123 45 6 78 91 011 12 131 4

提醒一下,我不想替换元素,而是在特定位置/索引之后添加一个新空间。

读取 .txt 文件并在 python 中的每一行的特定位置/索引后添加空格。

with open("C:/path-to-file/file.txt", "r") as file:
    lines = file.read().split("\n")
    newlines = []
    for line in lines:
        line = line.rstrip()
        newline = line[:] + ' ' + line[:]   # this line is incorrect
        newlines.append(newline)
    with open("C:/path-to-file/file.txt", "w") as newfile:  
        newfile.write("\n".join(newlines)

在文本文件的每一行的特定位置/索引之后添加空格

假设我的文件包含:

12345 678 91 011 12 1314

预期输出:

123 45 6 78 91 011 12 131 4

【问题讨论】:

    标签: python text-files readline


    【解决方案1】:

    考虑一下:

    space_indecies = [2, 5, 8]
    
    with open("C:/path-to-file/file.txt", "r") as file:
        lines = file.read().split("\n")
    newlines = []
    for line in lines:
        line = line.rstrip()
        for n, i in enumerate(space_indecies):
            line = line[:i + n] + ' ' + line[n + i:]
        newlines.append(line)
    with open("C:/path-to-file/file.txt", "w") as newfile:  
        newfile.write("\n".join(newlines))
    
    

    i + n 是必需的,因为您要插入空格的索引会随着插入的每个空格而变化

    【讨论】:

    • 拜托,能不能把整个代码写出来,因为出现这个语法错误:“unexpected EOF while parsing”!
    • 完成。现在就试试吧!
    • 出现此错误:line = line.rstrip() : invalid syntax !
    • 那是因为我已经离开了旧的解决方案。已删除。
    • 运行代码没有错误,但是文件没有执行!
    【解决方案2】:

    这是另一种使用生成器表达式的解决方案。

    如果您乐于在每个空格之后而不是之前提供索引列表,这将完成这项工作:

    line = '12345 678 91011 12 1314'
    idx = [3, 7, 12, 22]
    ' '.join([line[i:j] for i, j in zip([None]+idx, idx+[None])])
    

    给出'123 45 6 78 91 011 12 131 4'

    否则,您需要先向每个索引添加一个:

    idx = [2, 6, 11, 21]
    idx = [i+1 for i in idx]
    

    【讨论】:

    • 拜托,你能写完整的代码吗,因为出现这个语法错误:“unexpected EOF while parsing”!
    • 你可能复制了我删除的>>>
    • 很遗憾,我删除了它,这个错误仍然存​​在,请写完整代码并运行它来查看错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-08
    • 1970-01-01
    相关资源
    最近更新 更多