Python替换文件内的字符串内容

rep = ''
with open('1.txt', 'r') as fp:
  contents = fp.read()

  //read()方法读取所有内容,得到字符串。readline()读取一行内容,得到字符串。readlines()读取所有内容,按行得到字符串列表
  rep = contents.replace(' ', ',')

with open('1.txt', 'w') as fp2:

  //用'w'方式打开文件用于写入,写入时原文件的内容会被清空。 python没有writeline()、writelines()方法
  fp2.write(rep)

  

原文地址:https://www.cnblogs.com/zpf1092841490/p/14327612.html