简体   繁体   中英

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 ). 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]

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.
  • In the line line = line+"testing123" you only add the string to the local variable line .

So a possible solution can be to read all the lines, append the string and reopen the file to write to.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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