Reading Time: 1 minutes
Removing end-of-line characters from a file in Python
Removing end-of-line characters from a file: Write a Python program to create minified versions of files i.e. remove newline characters at end-of-line and bring all content in a single line.
Removing end-of-line characters from a file
# contents of style.css
body {
color: blue;
background: #000;
text-align: center;
}
## EXPECTED OUTPUT ##
body {color: blue; background: #000; text-align: center; }
fhTwo = open('style.css', 'w')
fhTwo.write('body {\n')
fhTwo.write('color: blue; \n')
fhTwo.write('background: #000; \n')
fhTwo.write('text-align: center; \n')
fhTwo.write('}')
fhTwo.close()
fH = open('style.css')
contents = fH.readlines()
newContents = []
for line in contents:
newContents.append(line.rstrip('\n'))
print("".join(newContents))
fH.close()
Try it here.







