save data to file

使用python 如何将数据输出到文件呢?
使用open以写模式或追加模式打开文件, 使用print的file=fileobj来写.
[root@localhost ~]# cd pydigoal/
[root@localhost pydigoal]# ll
total 16
drwxr-xr-x 3 root root   16 Jan 26 17:25 build
-rw-r--r-- 1 root root  404 Jan 29 22:36 digoal_nester.py
drwxr-xr-x 2 root root 4096 Jan 29 22:36 dist
-rw-r--r-- 1 root root   69 Jan 29 22:36 MANIFEST
-rw-r--r-- 1 root root  277 Jan 29 22:36 setup.py

修改之前写的digoal_nester.py
[root@localhost pydigoal]# vi digoal_nester.py 
import sys    # 导入sys模块, 默认print函数输出到sys.stdou, 即标准输出
"""this is comment
comment end"""

def print_lol(the_list, ident=False, level=0, fn=sys.stdout):    # 增加fn参数, 默认打印到标准输出
  """this is function comment
  comment end"""

  for each_item in the_list:
    if isinstance(each_item, list):
      print_lol(each_item, ident, level+1, fn)   # 加上fn参数
    else:
      if ident:
        for tab_stop in range(level):
          print("\t", end='', file=fn)   # 为print指定输出目标, file=fn
      print(each_item, file=fn)   # 为print指定输出目标, file=fn


修改setup.py
[root@localhost pydigoal]# vi setup.py 
from distutils.core import setup
setup(
    name = 'digoal_nester',
    version = '1.3.0',    # 修改版本号
    py_modules = ['digoal_nester'],
    author = 'digoal',
    author_email = 'digoal@126.com',
    url = 'http://blog.163.com/digoal@126',
    description = 'a test module by digoal'
)


上传到pypi
[root@localhost pydigoal]# python setup.py sdist upload
running sdist
running check
warning: sdist: manifest template 'MANIFEST.in' does not exist (using default file list)

warning: sdist: standard file not found: should have one of README, README.txt

writing manifest file 'MANIFEST'
creating digoal_nester-1.3.0
making hard links in digoal_nester-1.3.0...
hard linking digoal_nester.py -> digoal_nester-1.3.0
hard linking setup.py -> digoal_nester-1.3.0
Creating tar archive
removing 'digoal_nester-1.3.0' (and everything under it)
running upload
Submitting dist/digoal_nester-1.3.0.tar.gz to https://pypi.python.org/pypi
Server response (200): OK


本地安装digoal_nester模块
[root@localhost pydigoal]# python setup.py install
running install
running build
running build_py
copying digoal_nester.py -> build/lib
running install_lib
copying build/lib/digoal_nester.py -> /usr/local/lib/python3.4/site-packages
byte-compiling /usr/local/lib/python3.4/site-packages/digoal_nester.py to digoal_nester.cpython-34.pyc
running install_egg_info
Writing /usr/local/lib/python3.4/site-packages/digoal_nester-1.3.0-py3.4.egg-info


测试
[root@localhost pydigoal]# cd ..
[root@localhost ~]# vi test.py
import digoal_nester

l_list = ['hello',['i',['am','digoal']]]
digoal_nester.print_lol(l_list,True)

默认输出到标准输出
[root@localhost ~]# python ./test.py
hello
        i
                am
                digoal


改为输出到文件
[root@localhost ~]# vi test.py
import digoal_nester

l_list = ['hello',['i',['am','digoal']]]
with open("/tmp/abc.txt", "w") as f1:
  digoal_nester.print_lol(l_list,True,fn=f1)

[root@localhost ~]# python ./test.py
[root@localhost ~]# cat /tmp/abc.txt 
hello
        i
                am
                digoal

多次执行, 文件内容会被覆盖重写
[root@localhost ~]# python ./test.py
[root@localhost ~]# cat /tmp/abc.txt 
hello
        i
                am
                digoal

使用追加模式open("/tmp/abc.txt", "a"), 则会在文件末尾继续写.
[root@localhost ~]# python ./test.py
[root@localhost ~]# cat /tmp/abc.txt 
hello
        i
                am
                digoal
hello
        i
                am
                digoal


open打开文件的格式如下 : 
open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

>>>
>>> f = open('workfile', 'w')
The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. 
第一个参数是文件名, 第二个是文件的打开模式.
mode can be 'r' when the file will only be read, 只读
'w' for only writing (an existing file with the same name will be erased), 写模式, 会覆盖原内容.
and 'a' opens the file for appending; any data written to the file is automatically added to the end. 追加模式, 在文件末尾继续写.
'r+' opens the file for both reading and writing.  读写模式
The mode argument is optional; 'r' will be assumed if it’s omitted.


[其他]
1. len函数, 获得对象的长度
>>> print(len("hello"))
5

2. 字符串的strip方法, 用于截断字符串前后的空格
>>> print("  hello a b c   ".strip())
hello a b c

3. str()函数, 用于将对象转换为字符串, 例如
>>> try:
...   print(me)
... except NameError as err:
...   print("error" + str(err))  # +号对字符串对象, 用于连接字符串, 对数字对象, 用于数学运算
... 
errorname 'me' is not defined

>>> print(str(123))
123

4. in用于判断对象是否存在
>>> print("a" in ['a','b'])
True

5. locals()函数用于返回当前环境中的变量名列表
>>> print(locals())
{'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__package__': None, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__doc__': None}
>>> a=1
>>> print(locals())
{'__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'a': 1, '__package__': None, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__doc__': None}
>>> print(a in locals())
False
>>> print('a' in locals())  # 判断对象名是否存在本地变量中
True

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值