python file operate example - 1

本文示例, python对文本的操作.

先从数据库搞一些测试数据到文件中

postgres=# copy (select generate_series(1,1000)||','||md5(random()::text)) to '/home/postgres/test.txt';
COPY 1000

内容示例

postgres@localhost-> less /home/postgres/test.txt
1,891ca83e2c0971a8a0dc8d7e5edda338
2,75f9acd8d195f905b6ab6014ccef3a6b
3,ac4c2dc4d9de3461614d26a132f9c82f
4,41d48a6a19a061e1297339681173c491
5,756f8ed2d4dce954bb5af9793fbb6581
6,0f33bd2eae60c9f00a2824e777c27d02
7,24a75602d88008760ecb4043f1e47fa6
8,c51474a7d2f939ed97976ea67fdc554e

编写一个测试脚本, 将文件分割成2部分, 重新组合成其他格式

postgres@localhost-> vi test.py
import os

print(os.getcwd())  # 打印当前工作目录
os.chdir('/home/postgres')  # 修改当前工作目录
print(os.getcwd())

try:
  data=open('test.txt')  # 打开文件
  print(data.readline()) # 打印一行
  data.seek(0)  # 跳到文件开头
  for each_line in data:  # 每次读取一行
    try:
      (key,value)=each_line.split(',', 1)  # 使用第一个逗号作为分隔符, 分割成2个值
      print(key, end='')
      print(' is: ', end='')
      print(value, end='')
    except:
      pass
  data.close()  # 关闭文件
except:
  print('The file not exists')

其他, 

使用错误分类

except ValueError:

判断文件是否存在

os.path.exists('file')

测试结果如下 :

postgres@localhost-> python test.py |less
/home/postgres
/home/postgres
1,891ca83e2c0971a8a0dc8d7e5edda338

1 is: 891ca83e2c0971a8a0dc8d7e5edda338
2 is: 75f9acd8d195f905b6ab6014ccef3a6b
3 is: ac4c2dc4d9de3461614d26a132f9c82f
....
999 is: 44360dbdce1484cb8381f693e5f3237f
1000 is: 8bf252d6ba4d30ff18e7c5e3b067ef3e

小结 : 

Use the open()  BIF to open a disk file, creating an iterator that reads data from the file one line at a time.

 The readline()  method reads a single line from an opened file.

 The seek()  method can be used to “rewind” a file to the beginning.

 The close()  method closes a previously opened file.

 The split()  method can break a string into a list of parts.

 An unchangeable, constant list in Python is called a tuple. Once list data is assigned to a tuple, it cannot be changed.
 Tuples are immutable.

 A ValueError occurs when your data does not conform to an expected format.

 An IOError occurs when your data cannot be accessed properly (e.g., perhaps your data file has been moved or renamed).

 The help()  BIF provides access to Python’s documentation within the IDLE shell.

 The find()  method locates a specific substring within another string.
  查找字符串中包含某字符串的位置, -1表示未找到.

 The not keyword negates a condition.
  条件非, 例如 if not each_line.find(':') == -1 

 The try/except statement provides an exception-handling mechanism, allowing you to protect lines of code that might result in a runtime error.

 The pass statement is Python’s empty or null statement; it does nothing.
时间: 2024-08-12 13:06:43

python file operate example - 1的相关文章

python file operate example - 2

接上一篇文件操作例子, 这里主要是写入文件的例子. 将test.txt按照key的奇数和偶数分类写入两个文件. http://blog.163.com/digoal@126/blog/static/1638770402015027102245601/ postgres@localhost-> vi test.py import os # 导入os模块 even=[] # 定义两个list odd=[] print(os.getcwd()) # 打印当前工作目录 os.chdir('/home/p

[python]File文件操作

python中对文件.文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块. 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() 返回指定目录下的所有文件和目录名:os.listdir() 函数用来删除一个文件:os.remove() 删除多个目录:os.removedirs(r"c:\python") 检验给出的路径是否是一个文件:os.path.isfile() 检验给出的路径是否是一个目录:os.path.isdir() 判断是否是绝对路

找到个好的讲PYTHON FILE IO的文档,收藏

现在我感觉快入门了哈, 这两天,可以用PYTHON写一点自己想要实现的东东了. 但文件,IO,编码,邮件,始终有点续不完全. 这个文档,我看行.. http://www.dabeaz.com/python3io/ !!!  

python核心编程--笔记(不定时跟新)

的解释器options: 1.1 –d   提供调试输出 1.2 –O   生成优化的字节码(生成.pyo文件) 1.3 –S   不导入site模块以在启动时查找python路径 1.4 –v   冗余输出(导入语句详细追踪) 1.5 –m mod 将一个模块以脚本形式运行 1.6 –Q opt 除法选项(参阅文档) 1.7 –c cmd 运行以命令行字符串心事提交的python脚本 1.8 file   以给定的文件运行python脚本 2 _在解释器中表示最后一个表达式的值. 3 prin

Python基础(8)--文件

文件是我们储存信息的地方,我们经常要对文件进行读.写.删除等的操作,在Python中,我们可用Python提供的函数和方法方便地操作文件.文件可以通过调用open或file来打开,open通常比file更通用,因为file几乎都是为面向对象程序设计量身打造 本文地址:http://www.cnblogs.com/archimedes/p/python-file.html,转载请注明源地址. 文件处理的函数和方法 使用Open()函数可打开文件,语法格式如下: file_handler = ope

Python脚本文件打包成可执行文件的方法

  这篇文章主要介绍了Python脚本文件打包成可执行文件的方法,本主要讲解了Python2.X版本的打包方法,对Python3.X的打包也有简单介绍,需要的朋友可以参考下 将Python脚本文件包装成可执行文件,其目的有二: 一则: 不需要依赖Python编译器就可以运行软件 二则: 不想让自己的源码公布出去 常用的工具有: py2exe.cx_freeze等 [工具:py2exe] 安装py2exe 安装该工具很简单: 只需要从官方网站:http://www.py2exe.org/下载与版本

Python简单技巧和常用参考

 python文件支持中文 # -*- coding: UTF-8 -*- 执行shell命令 from subprocess import Popen, PIPE def run_cmd(cmd):     #Popen call wrapper.return (code, stdout, stderr)     child = Popen(cmd, stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = True)     out, err =

Python实现的批量下载RFC文档_python

RFC文档有很多,有时候在没有联网的情况下也想翻阅,只能下载一份留存本地了. 看了看地址列表,大概是这个范围: http://www.networksorcery.com/enp/rfc/rfc1000.txt ... http://www.networksorcery.com/enp/rfc/rfc6409.txt 哈哈,很适合批量下载,第一个想到的就是迅雷-- 可用的时候发现它只支持三位数的扩展(用的是迅雷7),我想要下的刚好是四位数-- 郁闷之下萌生自己做一个的想法! 这东西很适合用pyt

Python写的Tkinter程序屏幕居中方法_python

本文适用场景:想用Tkinter开发界面程序并屏幕居中,但没找到相应的API. 这两天玩了玩Tkinter,感觉不错,就是屏幕居中这个问题在网上搜了很长时间也没 找到答案,最后没办法,看它的文档,用自己的方法实现了. 方法很土,就是获取初始化的窗体大小和屏幕大小,再通过计算得到大体值. 以下是代码: 复制代码 代码如下: #! /usr/bin/python '''   File      : screenCenter.pyw   Author    : Mike   E-Mail    : M