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,
所以基本上我正在尝试开发对I / O的某种基本理解,我编写了这个程序,我正在尝试修复任何错误,
On line 11
在第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)
3 个解决方案
#1
open
is a built-in function. Do
open是一个内置函数。做
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.
提示:每个级别的缩进使用四个空格。
#2
Try another fh = open(...)
.
尝试另一个fh = open(...)。
open()
is a builtin function, not a file object attribute.
open()是内置函数,而不是文件对象属性。
#3
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
语法是可以的。但以下是我的评论1]如果你想读一个文件并将该文件写在另一个文件中。你将错过你的第一行。你需要关闭你正在更新的文件。 2]使用try ..除了代码中的块
#1
open
is a built-in function. Do
open是一个内置函数。做
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.
提示:每个级别的缩进使用四个空格。
#2
Try another fh = open(...)
.
尝试另一个fh = open(...)。
open()
is a builtin function, not a file object attribute.
open()是内置函数,而不是文件对象属性。
#3
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
语法是可以的。但以下是我的评论1]如果你想读一个文件并将该文件写在另一个文件中。你将错过你的第一行。你需要关闭你正在更新的文件。 2]使用try ..除了代码中的块