本文示例, 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-10-25 19:11:48