简体   繁体   English

python 未附加到目录中文件的每一行

[英]python not appending to each line in file in directory

I am trying to append a string ( "testing123" ) to each line of every file in my current working directory ( cache/configs ).我正在尝试 append 一个字符串( "testing123" )到我当前工作目录( cache/configs )中每个文件的每一行。 This is what I've done:这就是我所做的:

import os

for file in os.listdir('cache/configs'):
    with open('cache/configs/'+file, "r") as f:
        lines = f.readlines()
        for line in lines:
            line = line+"testing123"

The command goes through without error, but nothing is changing.该命令没有错误地执行,但没有任何变化。 At face value my logic seems cogent.从表面上看,我的逻辑似乎很有说服力。 Where am I going wrong?我哪里错了? Thanks.谢谢。

[Python version 3.6] [Python 3.6 版]

You're never saving the change.您永远不会保存更改。

import os

for file in os.listdir('cache/configs'):
    with open('cache/configs/'+file, "r+") as f:
        lines = f.readlines()
        for i, line in enumerate(lines):
            lines[i] = line.rstrip()+"testing123"
        f.writelines(lines)

Two things:两件事情:

  • You open de file as read only.您以只读方式打开 de 文件。
  • In the line line = line+"testing123" you only add the string to the local variable line .line = line+"testing123" ,您只需将字符串添加到局部变量line

So a possible solution can be to read all the lines, append the string and reopen the file to write to.因此,一个可能的解决方案是读取所有行 append 字符串并重新打开要写入的文件。

import os

for file in os.listdir('cache/configs'):

    temp_lines = []
    with open('cache/configs/'+file, "r") as f:
        lines = f.readlines()
        for line in lines:
            temp_lines.append(line+"testing123")

    with open('cache/configs/'+file, "w")  as f:
        f.writelines(temp_lines)

Shorter version, built on comment/answer of @alexisdevarennes较短的版本,基于@alexisdevarennes 的评论/回答

import os

for file in os.listdir('cache/configs'):

    with open('cache/configs/'+file, "r+") as f:
        lines = [l + "testing123" for l in f.readlines()]
        f.writelines(lines)

How about this?这个怎么样?

import os

for file in os.listdir('cache/configs'):
    cmd = "sed -i -e 's/$/ testing123/' cache/configs/{}".format(file)
    os.system(cmd)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM