-1

I just modified a text file using RegEx expressions in Google Collab. Specifically, I stripped a text file of three digit values. Now, I want to save the output and download the newly modified text file. How would I do this in Python?

For reference, here is my code.

filename = "gpt2historianregex.txt"

def main():
  fh = open("gpt2historianregex.txt")
  for line in fh:
    print( re. sub('\d{3}','', text), end='')


if __name__ == "__main__": main()
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 3
    Download from where? You are probably simply asking how to save the output; `python script.py >newfile.txt` runs `script.py` and saves its output in `newfile.txt` instead of printing it to the terminal. – tripleee May 06 '21 at 19:46
  • Sorry! I should clarify: I'm using Google Collab to run these expressions, so I've got the original text file hosted locally. I believe you're right! I am trying to save the output text as a file. – Grant Holt May 06 '21 at 19:59
  • 1
    `python script.py >newfile.txt` this is not Pythonic. OP could just use f.write() instead. – Feline May 06 '21 at 20:09

1 Answers1

0

To download the output, the file needs to be written first.

filename = "gpt2historianregex.txt"

def main():
  fh = open("gpt2historianregex.txt")
  with open('out_file.txt', 'w') as out:
      for line in fh:
        out.write(re.sub('\d{3}','', line), end=''))
  fh.close()




if __name__ == "__main__": main()

The file then should appear on the left bar in Google Colab.

Feline
  • 773
  • 3
  • 14
  • I seem to be running into an error. It says that "text" in the re.sub function is not defined, resulting in an error. Is it referring to the data type? Thank you so much for your help! – Grant Holt May 07 '21 at 00:09
  • It should be `line`; but this is a bug in your original code. – tripleee May 07 '21 at 03:06
  • I thought you gonna replace "text" with something. Like what they said in the comments, replace it with "line." – Feline May 07 '21 at 03:52