【问题标题】:what is the problem of this code? reading file in python这段代码有什么问题?在python中读取文件
【发布时间】:2022-12-31 21:47:24
【问题描述】:

此代码不起作用任何人都可以帮忙吗?

with open('file','rb') as a :
    try:
        while True:
            print(a.read(10)
    except:
        pass

【问题讨论】:

  • 请更清楚:您是否收到任何错误,如果是,请添加此类信息。
  • 只有一个空的 except 块从来都不是一个好主意。
  • 没有程序永远循环运行
  • 问题是你忘记了括号,这是一个错字,也请阅读什么是不存在的文件的异常并将其添加到 except 块中。
  • 忽略明显的语法错误,你想做什么?

标签: python


【解决方案1】:

使用这个来逐部分读取文件。

with open('file.txt', 'rb') as a: #
    i = 0
    while True:
        a.seek(i) # Going to the i index
        data = a.read(10) # Read the next part
        if not data: # break if data is empty else continue
            break
        print(data) # print data
        i += 10

这个一次读取整个文件,但逐部分打印

with open('file.TXT', 'rb') as a:

    data = a.read()  # Reading the whole data
    dataLength = len(data)
    i = 10  # Substring length
    while i < dataLength:

        if (i + 10) > dataLength:
            print(data[i:])
        else:
            print(data[i: i+10])
        i += 10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 2018-09-09
    相关资源
    最近更新 更多