0

I am trying to open a javascript(.js) file and remove all the tabs, new lines and white space from it, this is the code.

f1 = open('file1.js', 'r')
s = f1.read()
s.strip()
s.replace("\t", "")
s.replace(" ", "")
s.replace("\n", "")
f2 = open('file2.js', 'w+')
f2.write("//blobs\n"+s)
f1.close()
f2.close()

I do know that i am reading and writing it correctly because file2.js ends up as file1.js with //blobs as the first line. I have been searching for solutions but they all just point out that you can use strip() and replace()

thefourtheye
  • 233,700
  • 52
  • 457
  • 497

1 Answers1

1

Python's Strings are immutables. So, when you do any operation on a string, it will create a new string instead of making modifications on the original string. So, you might want to chain the changes, like this

with open('file1.js', 'r') as f1, open("file2.js", "w+") as f2:
    f2.write("//blobs\n" + f1.read().strip().replace("\t", "").replace("\n", ""))

Here, strip and replace create a new String object every time they are called. Now that we are doing the string operations on the newly created strings and finally creating a new String with blobs, the changes will be reflected in the "file2.js"

Note: I have used with statement to open files. Read more about the with statement in this answer

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497