繁体   English   中英

替换目录中所有文本文件的所有行中的字符串值

[英]Replace a string value from all the lines of all the text files in a directory

我有几个文件的内容。

文件01.txt

$ cat file01.txt
0 0.499594 0.154888 0.094968 0.156027
4 0.114448 0.101337 0.113636 0.035701
1 0.173701 0.154888 0.235390 0.068758
3 0.397727 0.669250 0.696429 0.063469

我想将目录中所有文件的所有行中的第一个字符的值替换为0 最pythonic的方法是什么?

预计 output

$ cat file01.txt
0 0.499594 0.154888 0.094968 0.156027
0 0.114448 0.101337 0.113636 0.035701
0 0.173701 0.154888 0.235390 0.068758
0 0.397727 0.669250 0.696429 0.063469
$ipython
In [1]: import os
    ...: files = [f for f in os.listdir('.') if os.path.isfile(f)]
    ...:
In [2]: print(files)
['file01.txt', 'file02.txt', 'file03.txt', ... ]
In [3]: for f in files:
    ...:     # writing files to another directory called "new"
    ...:     with open('new/'+ f, 'w') as fwrite, open(f) as fread:
    ...:         for line in fread:
    ...:             nline = '0' + line[1::]
    ...:             fwrite.write(nline)
    ...:

$ cat file01.txt
0 0.499594 0.154888 0.094968 0.156027
0 0.114448 0.101337 0.113636 0.035701
0 0.173701 0.154888 0.235390 0.068758
0 0.397727 0.669250 0.696429 0.063469

# similarly text in other files will also show the change.

暂无
暂无

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

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