Python读取文件内容 [英] Python Read File Content

查看:60
本文介绍了Python读取文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,如何像在Java中使用InputStream一样仅读取文件内容(不包括属性和文件名)?我需要一种适用于各种文件格式的方法

In Python, how to read a file content only (not including attribute and filename), like using InputStream in Java? I need a method that works for various file formats

我已经尝试过了

with open(filePath, "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    M=str.decode()
    print(M)

问题是,在该块之后,任何对象都会出错

The problem is, I will get error for any object after that block

推荐答案

最基本的方法如下:

with open("filename.txt") as f:
    contents = f.read()

变量内容现在将包含文件中所有内容的字符串.有关更多信息,请参见Python文档( https://docs.python.org/3/tutorial/inputoutput.html ).

The variable contents will now contain a string of everything in the file. More information is in the Python Documentation (https://docs.python.org/3/tutorial/inputoutput.html).

这篇关于Python读取文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆