简体   繁体   中英

How to replace first column in text file?

I have file like this

6     5     1         2.364       0.022
6     5     2        30.364       2.866
6     5     5         2.351       0.022
6     5     6        44.606       2.866
6     6     1         2.372       0.022
6     6     2        33.290       2.866
6     6     5         2.290       0.022
6     6     6        43.799       2.866
6     7     1         2.414       0.022
6     7     2        37.071       2.866
6     7     5         2.281       0.022

I want to change 6 to 1.I have thought of

line.contains

but 6 also appears in other columns.

我建议使用sed而不是 Python。

sed -e 's/^6/1/' input.txt > output.txt
import re
with open(...) as f:
    print re.sub('^6', '1', f.read(), flags=re.MULTILINE)

s = '''6     5     1         2.364       0.022
6     5     2        30.364       2.866
6     5     5         2.351       0.022
6     5     6        44.606       2.866
6     6     1         2.372       0.022
6     6     2        33.290       2.866
6     6     5         2.290       0.022
6     6     6        43.799       2.866
6     7     1         2.414       0.022
6     7     2        37.071       2.866
6     7     5         2.281       0.022'''

import re
print re.sub('^6', '1', s, flags=re.MULTILINE)

And if you don't want to use re , you could try (although I would recommend to use re ) :

lines = []
for line in open(...):
    parts = line.split()
    parts[0] = '1'
    lines.append('\t'.join(parts))
 print '\n'.join(lines)

or:

lines = []
for line in open(...):
    lines.append(line.replace('6', '1', 1))
 print '\n'.join(lines)

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