简体   繁体   中英

How to save the file using fileinput in python? Giving AttributeError: 'FileInput' object has no attribute 'read'

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()

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM