分页: 1 / 1

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

发表于 : 2007-11-03 17:19
yunpengwu
需求是从一个配置文件中读取结构化的数据。
php的一种方式是将数据文件写为返回一个php数组的方式。工作文件只需要include这个数据文件就可以直接使用这个php数据。
不知道python有没有类似这种简单的方法?

发表于 : 2007-11-03 22:25
dbzhang800
不知道你所谓的结构话的数据是指什么,

不过python肯定能处理你的问题,只要你的文件不比xml,sgml,html等文件复杂

发表于 : 2007-11-06 11:52
cozo
脚本语言都有动态运行的能力,你把配置文件存成Python的代码,import一下不就得了,等于PHP的Include。

发表于 : 2007-11-06 12:55
yunpengwu
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
        )

)

发表于 : 2007-11-11 9:16
isnull
struct模块

发表于 : 2007-11-19 11:35
joo.tsao
你查一下Picker模块,支持任意对象的序列化(包括存储为文件以及反之)。

发表于 : 2008-01-16 10:09
SuperWar3Fan
这个好像在TAOU里面有一个fetchmail的配置例子,非常经典。

发表于 : 2008-01-16 22:50
anticlockwise
如果你想要得就是像你说的php include那样的方法的话,Python不也一样吗?用import

a.py

代码: 全选

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

代码: 全选

from a import *
print array

发表于 : 2008-02-11 5:48
frank7258

代码: 全选

#!/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