用于打开/创建文本, 可执行 读("r"), 写("w"), 加("a") 功能, 默认为("r")
read(), readline(), readlines()
read() - 读全文
readline() - 读每一行
readlines() - 读每一行, 并返回为列表(list)
>>> f=open("newtext.txt", "w")
>>> f.write("hello world!")
r: Opens the file in read-only mode. Starts reading from the beginning of the file and is the default mode for the open() function.
wb: Opens a write-only file in binary mode.
w+: Opens a file for writing and reading.
a: Opens a file for appending new information to it. The pointer is placed at the end of the file. A new file is created if one with the same name doesn't exist.
json.dump, json.load
json.dumps, json.loads
Read/Write from file:
import json
with open('data.txt', 'w') as f:
json.dump(dict1, f)
with open('data.txt', 'r') as f:
dict1=json.load(f)
json.dumps, json.loads 用于直接操作 json 格式数据 在python中,使其 human可读:
>>> print(json.dumps(data, sort_keys=True, indent=2))
{
"item": "Beer",
"cost": "£4.00"
}
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]
cat ./output/pre_file_name.json | python -m json.tool
list_UC.txt
edn1-uc-cup01
edn1-uc-cucm02
esg3-uc-cuc01
playbook.yml
with open("./list_UC") as file: # Use file to refer to the file object
Targets = file.readlines()
print (Targets)
for host in Targets:
print (host.strip())
注意! w/a 模式无法读取文件内容。
>>> print (f.read())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: File not open for reading
必须改为 “r” 模式打开
>>> f1=open("newtext.txt","r")
>>> print (f1.readlines())
['Hello world!']
输出一遍后指针会停留在末尾,利用seek(0) 吧指针调回起始点, 或者使用with 语句.
>>> f1=open("newtext.txt","w")
>>> f1.write("Hello World!")
>>> f1=open("newtext.txt","a")
>>> f1.write("\n")
>>> f1.write("This is AirBnB Dublin")
>>> f1=open("newtext.txt","r")
>>> print (f1.read())
Hello World!
This is AirBnB Dublin
>>>print (f1.read())
>>> f1.seek(0)
>>> print (f1.read())
Hello World!
This is AirBnB Dublin
======================================================
>>> with open("newtext.txt") as f2:
... print (f2.read())
...
Hello World!
This is AirBnB Dublin