0

Replacing the first line of a text file python-2.7 keeps adding a \r character without the \n. How do I get \r\n for a windows text file?

What would change with python v3?

WARNING - DON'T USE THIS CODE TO CHANGE FIRST LINE - IT TRUNCATES FILES

# Replace first line in text file with filename
#
import os
import sys
import shutil

# Initialise
src = open(sys.argv[1])

line = src.readline()
# make any changes to line here
line = sys.argv[1]

dst = open(sys.argv[1],mode="w")
dst.write(line)
shutil.copyfileobj(src, dst)

line = sys.argv[1]+'\r\n' gives a \n on one line and a \r\n on the next.

Reference: change first line of a file in python

flywire
  • 1,155
  • 1
  • 14
  • 38

1 Answers1

0

After searching all over the place I finally worked it out. I expected the 'import os' would have sorted it out.

line = sys.argv[1]+'\n'
flywire
  • 1,155
  • 1
  • 14
  • 38