1

I am saving the file using fileinput module but throwing AttributeError: 'FileInput' object has no attribute 'read'

i have closed the file by looking into some stack overflow questions

 import re
 import fileinput
 rx = r'\d+(?=:$)'
 with fileinput.input('branch.txt', inplace=True) as fh:
    data = fh.read()
    print(re.sub(rx , lambda x: str(int(x.group(0)) + 1), data, 1, re.M))
    data.close()
    fh.close

if I am using normal mode i am getting io.UnsupportedOperation: not readable

 import re
 rx = r'\d+(?=:$)'
 with open('branch.txt','a') as fh:
    fh_n = fh.read()
    x = (re.sub(rx, lambda x: str(int(x.group(0)) + 1), fh_n, 1, re.M))
    #print (x)
    fh.write(x)
    fh.close()
  • 3
    Why do you want `fileinput` instead of builtin `open`? – stasdeep Jun 24 '19 at 13:04
  • import re rx = r'\d+(?=:$)' with open('branch.txt','a') as fh: fh_n = fh.read() x = (re.sub(rx, lambda x: str(int(x.group(0)) + 1), fh_n, 1, re.M)) print (x) fh.write(x) fh.close() got error io.UnsupportedOperation: not readable –  Jun 24 '19 at 13:14
  • 1
    So, all you want is to read and write to the same file? See [Search and replace a line in a file in Python](https://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python) – Wiktor Stribiżew Jun 24 '19 at 13:16
  • Yes, i m trying to do that. Is there any issue in code. because read mode perfectly working fine –  Jun 24 '19 at 13:17

1 Answers1

0

if I am using normal mode i am getting io.UnsupportedOperation: not readable

 import re
 …
 with open('branch.txt','a') as fh:

That's because one cannot read from a file opened with mode 'a' (append).

Armali
  • 18,255
  • 14
  • 57
  • 171