Python3 文件基本修改替换

现有原文件:

 1 Somehow, it seems the love I knew was always the most destructive kind
 2 不知为何,我经历的爱情总是最具毁灭性的的那种
 3 Yesterday when I was young
 4 昨日当我年少轻狂
 5 The taste of life was sweet
 6 生命的滋味是甜的
 7 As rain upon my tongue
 8 就如舌尖上的雨露
 9 I teased at life as if it were a foolish game
10 我戏弄生命 视其为愚蠢的游戏
11 The way the evening breeze
12 就如夜晚的微风
13 May tease the candle flame
14 逗弄蜡烛的火苗
15 The thousand dreams I dreamed
16 我曾千万次梦见
17 The splendid things I planned
18 那些我计划的绚丽蓝图
19 I always built to last on weak and shifting sand
20 但我总是将之建筑在易逝的流沙上
21 I lived by night and shunned the naked light of day
22 我夜夜笙歌 逃避白昼赤裸的阳光
23 And only now I see how the time ran away
24 事到如今我才看清岁月是如何匆匆流逝
25 Yesterday when I was young
26 昨日当我年少轻狂
27 So many lovely songs were waiting to be sung
28 有那么多甜美的曲儿等我歌唱
29 So many wild pleasures lay in store for me
30 有那么多肆意的快乐等我享受
31 And so much pain my eyes refused to see
32 还有那么多痛苦 我的双眼却视而不见
33 I ran so fast that time and youth at last ran out
34 我飞快地奔走 最终时光与青春消逝殆尽
35 I never stopped to think what life was all about
36 我从未停下脚步去思考生命的意义
37 And every conversation that I can now recall
38 如今回想起的所有对话
39 Concerned itself with me and nothing else at all
40 除了和我相关的 什么都记不得了
41 The game of love I played with arrogance and pride
42 我用自负和傲慢玩着爱情的游戏
43 And every flame I lit too quickly, quickly died
44 所有我点燃的火焰都熄灭得太快
45 The friends I made all somehow seemed to slip away
46 所有我交的朋友似乎都不知不觉地离开了
47 And only now I'm left alone to end the play, yeah
48 只剩我一个人在台上来结束这场闹剧
49 Oh, yesterday when I was young
50 噢 昨日当我年少轻狂
51 So many, many songs were waiting to be sung
52 有那么那么多甜美的曲儿等我歌唱
53 So many wild pleasures lay in store for me
54 有那么多肆意的快乐等我享受
55 And so much pain my eyes refused to see
56 还有那么多痛苦 我的双眼却视而不见
57 There are so many songs in me that won't be sung
58 我有太多歌曲永远不会被唱起
59 I feel the bitter taste of tears upon my tongue
60 我尝到了舌尖泪水的苦涩滋味
61 The time has come for me to pay for yesterday
62 终于到了付出代价的时间 为了昨日
63 When I was young
64 当我年少轻狂
View Code

如果我们要修改其中一些文字,可以运用以下:

1 y = open('yesterday','r')
2 y_new = open('yesterday_new','w')
3 tihuan = input('输入要替换的替换:')
4 tihuan_new = input('输入要替换的替换:')
5 
6 for i in y:
7     if tihuan in i:
8         i = i.replace(tihuan,tihuan_new)
9     y_new.write(i)

找出yesterday文件,如果要修改什么,可以input输入:,比如要修改其中的

1 So many wild pleasures lay in store for me
2 有那么多肆意的快乐等我享受

把我修改成Tuskasa:

可以

tihuan = input('输入要替换的替换:')
输入:有那么多肆意的快乐等我享受
再输入:有那么多肆意的快乐等Tuskasa享受
就会创建一个新的文件并修改(注意是创建一个新的文件,这样我们就可以保存原文件,避免丢失)

或者可以另外定义:
 1 import sys
 2 find_str = sys.argv[1]
 3 replace_str = sys.argv[2]
 4 
 5 y = open('yesterday','r')
 6 y_new = open('yesterday_new','w')
 7 
 8 for i in y:
 9     if find_str in i:
10         i = i.replace(find_str,replace_str)
11     y_new.write(i)

注意一定要记得close()文件

原文地址:https://www.cnblogs.com/Tsukasa/p/6575970.html