【问题标题】:Python cant read file TypeError: object of type 'file' has no len() [duplicate]Python无法读取文件TypeError:'file'类型的对象没有len()[重复]
【发布时间】:2015-04-22 03:57:21
【问题描述】:
from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

in_file = open(from_file, 'w')


print "The input file is %d bytes long" % len(in_file)

print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()

out_file = open(to_file, 'w')
out_file.write(in_file)

print "Alright, all done."

out_file.close()
in_file.close()

我得到的错误 TypeError: 'file' 类型的对象没有 len()

我已将 in_file 变量设置为写入模式,所以我不明白问题出在哪里。

【问题讨论】:

  • 如果你说它是重复的,也许可以发送一个链接到“重复”并回答问题?
  • 链接在问题的顶部。

标签: python


【解决方案1】:

您需要以读取模式打开文件。

in_file = open(from_file)
f =  in_file.read()
print "The input file is %d bytes long" % len(f)

【讨论】:

  • 感谢您的帮助。
【解决方案2】:

您必须以读取模式打开文件,然后才能读取文件内容并计算内容大小:

in_file = open(from_file, 'r')
f = in_file.read()
print "The input file is %d bytes long" % len(f)

有关文件大小,请查看:link

【讨论】:

  • 感谢您的帮助。
猜你喜欢
  • 2019-01-06
  • 1970-01-01
  • 2015-01-21
  • 2020-04-18
  • 2021-03-03
  • 2015-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多