简体   繁体   中英

Keep getting attribute error when trying to use I/O

So basically I am trying to develop some sort of basic understanding of I/O, I wrote this program and I'm trying to fix any bugs,

On line 11

fh.open('updated' + filename, 'w')

I keep getting an

AttributeError: '_io.TextIOWrapper' object has no attribute 'open'

whats wrong and how do i fix it? Also if there are any additional errors(not syntax) that you see, let me know!

filename = 'sample.txt'
fh = open(filename, 'r')
lines = fh.readlines()
x = 0
for i in lines:
  if i == '\n':
    lines[x] = lines[x]*2
  else:
    lines[x] = ''
fh.close()
fh.open('updated' + filename, 'w')
for line in lines:
  fh.write(line)

open is a built-in function. Do

fh = open('updated' + filename, 'w')

Even better:

with open('updated' + filename, 'w') as fh:
    fh.write(line)

Hint: Use four spaces for each level of indention.

Try another fh = open(...) .

open() is a builtin function, not a file object attribute.

Syntax is okay.But following are my comments
1] If you want to read one file and write that file in another file.You will miss first line in your case.As well as you need to close your file is which you are updating.
2] Use try .. except blocks in your code

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