python - 使用python从文件中读取数据

标签 python

无法使用Python从文件中读取所有数据

在 test.txt 中有:

{'God': {u'user1@localhost': {}, u'user2@localhost': {}, u'user3@localhost': {}}}

代码是:

# coding: utf-8

def read_file(filename):
    data=None
    try:
        fp = file(filename)
        data = fp.read()
        fp.close()
    except: pass
    return data

def read():
    file = 'test.txt'
    db = eval(read_file(file))
    if "God" in db:
        for x in db["God"]:
            data = x
            #print(x) $$ it'll print all data True but I do not need it, I will put instructions inside and I do not need to be repeated.
        print(x) # $$ print just 1 data from file

try: read()
except: pass

如何让它读取文件中的所有数据

谢谢。

最佳答案

要从文本文件中读取所有数据,只需使用 read文件对象的方法,例如

with open('test.txt','r') as f:
    file_content = f.read()

关于python - 使用python从文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28314186/

相关文章:

Python 适合给定输入的数据类型

c++ - ImportError undefined symbol PyUnicodeUCS2_FromObject

python - 使用 "if x in (y, z)"会比使用 "if x == y or x == z"更好吗?

python - matplotlib 设置图例颜色

python - AWS IoT 设备未收到 iOS 应用程序发布的消息

python - 从段落中提取热字符之间的多个字符串

python - wxPython菜单文本对齐

python - google app engine 将大数据放入数据存储区的有效方法

Python 类与 numpy 数组求和

python - 编辑 NLTK 语料库