python

导航

在python怎么把/r/n替换成/n?

来源 :中华考试网 2020-10-05

  Python怎么把/r/n替换成/n?

  在文本编辑器中会自动将\r\n截断成\n,(在unix上换行使用\n,windows上,换行使用的是\r\n)于是,写了这个脚本,不用一行一行去改。来具体看下如何实现的:

  import os

  def replace(filePath, w2u):

  try:

  oldfile = open(filePath, "rb+") #这里必须用b打开

  path, name = os.path.split(filePath)

  newfile = open(path + '$' + name, "ba+")

  old = b''

  new = b''

  if w2u == True:

  old = b'\r'

  new = b''

  else:

  old = b'\n'

  new = b'\r\n'

  data = b''

  while (True):

  data = oldfile.read(200)

  newData = data.replace(old, new)

  newfile.write(newData)

  if len(data) < 200:

  break

  newfile.close()

  oldfile.close()

  os.remove(filePath)

  os.rename(path + '$' + name, filePath)

  except IOError as e:

  print(e)

  if __name__ == "__main__":

  print("请输入文件路径:")

  filePath = input()

  replace(filePath, False) #这个改为True就可以实现\n变成\r\n

  要注意的是,在python里,像\r\n这样的符号,如果是文本打开的话,是找不到\r\n的,而只能找到'\n',所以必须用b(二进制)模式打开。

分享到

相关资讯