python最简单的从文件中读取数据的方式是什么?

软件和网站开发以及相关技术探讨
回复
yunpengwu
帖子: 294
注册时间: 2007-08-26 10:35
来自: 上海
联系:

python最简单的从文件中读取数据的方式是什么?

#1

帖子 yunpengwu » 2007-11-03 17:19

需求是从一个配置文件中读取结构化的数据。
php的一种方式是将数据文件写为返回一个php数组的方式。工作文件只需要include这个数据文件就可以直接使用这个php数据。
不知道python有没有类似这种简单的方法?
dbzhang800
帖子: 3182
注册时间: 2006-03-10 15:10
来自: xi'an China
联系:

#2

帖子 dbzhang800 » 2007-11-03 22:25

不知道你所谓的结构话的数据是指什么,

不过python肯定能处理你的问题,只要你的文件不比xml,sgml,html等文件复杂
cozo
帖子: 20
注册时间: 2007-11-02 10:16

#3

帖子 cozo » 2007-11-06 11:52

脚本语言都有动态运行的能力,你把配置文件存成Python的代码,import一下不就得了,等于PHP的Include。
yunpengwu
帖子: 294
注册时间: 2007-08-26 10:35
来自: 上海
联系:

#4

帖子 yunpengwu » 2007-11-06 12:55

cozo 写了:脚本语言都有动态运行的能力,你把配置文件存成Python的代码,import一下不就得了,等于PHP的Include。
能不能说的具体一点,比如说php中的例子:
a.php:

代码: 全选

<?php
    return array(
        array('name' => 'abc', 'code' => 12),
        array('name' => 'xyz', 'code' => 34)
    );
b.php

代码: 全选

<?php
    $list = include('a.php');
    print_r($list);
运行php b.php即可得:

代码: 全选

Array
(
    [0] => Array
        (
            [name] => abc
            [code] => 12
        )

    [1] => Array
        (
            [name] => xyz
            [code] => 34
        )

)
isnull
帖子: 34
注册时间: 2007-07-16 15:24

#5

帖子 isnull » 2007-11-11 9:16

struct模块
joo.tsao
帖子: 37
注册时间: 2007-03-18 22:39

#6

帖子 joo.tsao » 2007-11-19 11:35

你查一下Picker模块,支持任意对象的序列化(包括存储为文件以及反之)。
头像
SuperWar3Fan
帖子: 1263
注册时间: 2006-05-20 6:25
来自: 山东淄博
联系:

#7

帖子 SuperWar3Fan » 2008-01-16 10:09

这个好像在TAOU里面有一个fetchmail的配置例子,非常经典。
头像
anticlockwise
帖子: 2394
注册时间: 2007-03-01 20:46
来自: 湖南长沙

#8

帖子 anticlockwise » 2008-01-16 22:50

如果你想要得就是像你说的php include那样的方法的话,Python不也一样吗?用import

a.py

代码: 全选

array = [{'name' : 'abc', 'code' : 12},\
    {'name' : 'xyz', 'code' : 34}]
b.py

代码: 全选

from a import *
print array
头像
frank7258
帖子: 61
注册时间: 2007-01-31 23:01
来自: 慕尼黑
联系:

#9

帖子 frank7258 » 2008-02-11 5:48

代码: 全选

#!/usr/bin/python
# Filename: pickling.py

import cPickle as p
#import pickle as p

shoplistfile = 'shoplist.data'
# the name of the file where we will store the object

shoplist = ['apple', 'mango', 'carrot']

# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close()

del shoplist # remove the shoplist

# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist 
from http://www.woodpecker.org.cn:9081/doc/a ... 12s02.html
回复