python文件操作
相对路径,‘/’,‘./’,‘…/’
“/”:表示根目录,在windows系统下表示某个盘的根目录,如“E:\”;
“./”:表示当前目录;(表示当前目录时,也可以去掉“./”,直接写文件名或者下级目录)
“…/”:表示上级目录。
if __name__ == '__main__':
f1 = open('file1.txt', 'w', encoding='utf-8')
f1.write('当前目录?\n')
f1.write('true')
f1.close()
# macOS系统下,不推荐在根目录直接创建文件,会产生PermissionError: [Errno 13] Permission denied,但可以在一些允许读写的文件夹下面操作,如'/Users/wuliytTaotao/Desktop/file2.txt'。
f2 = open('/file2.txt', 'w', encoding='utf-8')
f2.write('在哪儿?\n')
f2.write('在根目录,windows系统下就是在某个盘的根目录下,如E:\\file2.txt')
f2.close()
f3 = open('./file3.txt', 'w', encoding='utf-8')
f3.write('当前目录?\n')
f3.write('yes')
f3.close()
f4 = open('../file4.txt', 'w', encoding='utf-8')
f4.write('在哪儿?\n')
f4.write('该.py文件所在位置的上级目录')
f4.close()
代码执行完后,可以发现生成的文件位置如下图所示:(上述代码保存在 tmp.py 文件中)
文件“file2.txt”可以在“E:\”目录下找到。
References:https://blog.youkuaiyun.com/Fighting_Yaya/article/details/80275304
Python中获得当前目录和上级目录
获取当前文件的路径:
from os import path
d = path.dirname(__file__) #返回当前文件所在的目录
# __file__ 为当前文件, 若果在ide中运行此行会报错,可改为 #d = path.dirname('.')
获得某个路径的父级目录:
parent_path = os.path.dirname(d) #获得d所在的目录,即d的父级目录
parent_path = os.path.dirname(parent_path) ##获得parent_path所在的目录即parent_path的父级目录
获得规范的绝对路径:
abspath = path.abspath(d) #返回d所在目录规范的绝对路径
原文地址:http://blog.youkuaiyun.com/liuweiyuxiang/article/details/71154346
Python逐行读取文件内容
来源:https://www.cnblogs.com/shgq/p/4095764.html
f = open("foo.txt") # 返回一个文件对象
line = f.readline() # 调用文件的 readline()方法
while line:
print line, # 后面跟 ',' 将忽略换行符
# print(line, end = '') # 在 Python 3中使用
line = f.readline()
f.close()
也可以写成以下更简洁的形式
for line in open("foo.txt"):
print line,
更详细的文件按行读取操作可以参考:http://www.cnblogs.com/xuxn/archive/2011/07/27/read-a-file-with-python.html
1. 最基本的读文件方法:
?
# File: readline-example-1.py
file = open("sample.txt")
while 1:
line = file.readline()
if not line:
break
pass # do something
一行一行得从文件读数据,显然比较慢;不过很省内存。
在我的机器上读10M的sample.txt文件,每秒大约读32000行
2. 用fileinput模块
?
# File: readline-example-2.py
import fileinput
for line in fileinput.input("sample.txt"):
pass
写法简单一些,不过测试以后发现每秒只能读13000行数据,效率比上一种方法慢了两倍多……
3. 带缓存的文件读取
?
# File: readline-example-3.py
file = open("sample.txt")
while 1:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
pass # do something
这个方法真的更好吗?事实证明,用同样的数据测试,它每秒可以读96900行数据!效率是第一种方法的3倍,第二种方法的7倍!
————————————————————————————————————————————————————————————
在Python 2.2以后,我们可以直接对一个file对象使用for循环读每行数据:
?
# File: readline-example-5.py
file = open("sample.txt")
for line in file:
pass # do something
而在Python 2.1里,你只能用xreadlines迭代器来实现:
?
# File: readline-example-4.py
file = open("sample.txt")
for line in file.xreadlines():
pass # do something
python读写json文件
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C、C++、Java、JavaScript、Perl、Python等)。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)。
JSON在python中分别由list和dict组成。
这是用于序列化的两个模块:
- json: 用于字符串和python数据类型间进行转换
- pickle: 用于python特有的类型和python的数据类型间进行转换
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
json dumps把数据类型转换成字符串 dump把数据类型转换成字符串并存储在文件中 loads把字符串转换成数据类型 load把文件打开从字符串转换成数据类型
json是可以在不同语言之间交换数据的,而pickle只在python之间使用。json只能序列化最基本的数据类型,josn只能把常用的数据类型序列化(列表、字典、列表、字符串、数字、),比如日期格式、类对象!josn就不行了。而pickle可以序列化所有的数据类型,包括类,函数都可以序列化。
事例:
dumps:将python中的 字典 转换为 字符串
1 import json
2
3 test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
4 print(test_dict)
5 print(type(test_dict))
6 #dumps 将数据转换成字符串
7 json_str = json.dumps(test_dict)
8 print(json_str)
9 print(type(json_str))
1 new_dict = json.loads(json_str)
2 print(new_dict)
3 print(type(new_dict))
1 with open("../config/record.json","w") as f:
2 json.dump(new_dict,f)
3 print("加载入文件完成...")
load:把文件打开,并把字符串变换为数据类型
1 with open("../config/record.json",'r') as load_f:
2 load_dict = json.load(load_f)
3 print(load_dict)
4 load_dict['smallberg'] = [8200,{1:[['Python',81],['shirt',300]]}]
5 print(load_dict)
6
7 with open("../config/record.json","w") as dump_f:
8 json.dump(load_dict,dump_f)