Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Remove digits and decimals from text file

i wrote this code to remove digits and dots from a text file

import fileinput


for line in fileinput.input("/content/drive/MyDrive/011186973309203002021041922243182.txt", inplace=True):
    
    #remove digits
    result = ''.join(i for i in line if not i.isdigit())
    #remove . 
    result = result.replace(".","")
    print(result)

but im not getting any results why is that ? i cant see the issue. it is literally printing nothing like its empty what can i do ?

this is an example for the text file im running

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

text sample

i get these error the first time i run the code

1-

UnicodeEncodeError: ‘charmap’ codec can’t encode characters in
position 45-49: character maps to

RuntimeError: input() already active

>Solution :

Try to remove the inplace=True from your function call. According to the fileinput documentation

"if the keyword argument inplace=True is passed to fileinput.input()
or to the FileInput constructor, the file is moved to a backup file
and standard output is directed to the input file (if a file of the
same name as the backup file already exists, it will be replaced
silently). This makes it possible to write a filter that rewrites its
input file in place"

So printing will not work, as everything is being piped to your input file.

Also depending on your use case, fileinput may not be the most appropriate module to use. Again, referring to the fileinput documentation:

This module implements a helper class and functions to quickly write a
loop over standard input or a list of files. If you just want to read
or write one file see open().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading