python文件和元組


  • python文件操作

相較於java,Python里的文件操作簡單了很多

python 獲取當前文件所在的文件夾:

os.path.dirname(__file__)

寫了一個工具類,用來在當前文件夾下生成文件,這樣方便

class Util():
    """工具類"""

    @classmethod
    def get_file_url(cls, file_name):
        """獲取當前文件夾的路徑"""
        return os.path.join(os.path.dirname(__file__), file_name)

向一個文件中寫數據,w表示write,用於寫入

myfile = open("a.txt", "w")
myfile.write("hello2 world \n")
myfile.write("good bye \n")

打開文件查看內容為

寫完文件后如果不在操作文件,記得關閉文件,養成好習慣。

myfile.close()

一般文件的讀取都是放在try-except塊中的,其中文件的關閉放在finally 中,這樣能保證文件始終是關閉的。

讀取文件

myfile = open(Util.get_file_url("a.txt"),'r')
print "第一行",myfile.readline() # 讀取第一行
print "第二行",myfile.readline() # 讀取第二行
print "所有行",myfile.read()
readline()方法一次讀取文件中的一行,由於文件只有2行,所以執行2次readline()后沒有再可以讀的數據了,read()方法會將文件的所有內容讀入一個字符串。如果要講文件指針重置
到最開始的位置,可以使用如下方法
myfile.seek(0) # 將文件重置到最開始的地方

read() 方法可以指定讀取的字節大小,如read(6)

myfile = open(Util.get_file_url("aaa.xxx"),'r')
new_str = myfile.read(6) # aaa.xxx的內容為"你好",讀取6個字節則可以剛好將字符串讀出來,一個中文3個字節

 

使用迭代器讀取文件

iterator = open(Util.get_file_url("aaa.xxx"),'r')
for line in iterator:
    print line

讀取文件到字符串列表

lines = myfile.readlines() # 將文件的每一行作為一個元素存入列表中
  • 用pickle存儲python的原聲對象
class Person(object):
    def __init__(self, name='', age=0):
        self.age = age
        self.name = name

    def __str__(self):
        return self.name+" -- "+str(self.age)


p = Person('zhangsan', 24)
p.sex = ''
p.salary = 12000

# 將對象存入文件
to_file = open(Util.get_file_url("aaa.txt"),'wb')
pickle.dump(p, to_file)
to_file.close()
print p.name
# 將存入文件中的對象load進來
from_file = open(Util.get_file_url("aaa.txt"),'rb') # rb 表示讀取二進制文件
person = pickle.load(from_file)
print person
  • 元組操作(tuple)

元組的存在組要是為列表提供完整性,元組具有不可變性,可以確保在程序中不會被另一個引用修改。它類似於其他語言中的常數。

元組的在python中屬於tuple 類型常見的操作:

# 元組定義
tuple1 = ()  # 空的元組
tuple2 = (1,)  # 包含1個元素的元組
int1 = (1)  # 包含一個元素的變量
tuple4 = (1, 2, 3, 4,2)
# 遍歷元組
for tup in tuple4:
    print tup
print '*' * 55
# 獲取指定下標的元素
print tuple4[2]
# 獲取指定數的下標
print tuple4.index(4)

# 獲取指定值出現的次數
print tuple4.count(2)

print tuple4[1:3]  # 含左不含右
  • 簡介python 列表中的引用和拷貝

python中一切皆為對象,賦值只是拷貝了引用。舉個例子:

>>> list1=[1,2,3,4]
>>> print list1
[1, 2, 3, 4]
>>> x = list1
>>> print x
[1, 2, 3, 4]
>>> list1[1]='abc'
>>> print list1
[1, 'abc', 3, 4]
>>> print x
[1, 'abc', 3, 4]

如果有其他面向對象編程的經驗就不難理解,那么如何將list1列表完全賦值給x呢,我們可以使用如下的方法

>>> x = list(list1)  (也可以 x = list1[:]) >>> print x
[1, 'abc', 3, 4]
>>> list1[1]=2
>>> print list1
[1, 2, 3, 4]
>>> print x
[1, 'abc', 3, 4]

對於dict 類型,可以使用如下的方式,這樣就實現了完整的拷貝

>>> dict1 = {"a":1,"b":2}
>>> dict2 = dict1.copy()

注意:通過 copy 和 list() 或list1[:]的方式生成的只是頂層拷貝,並不能賦值嵌套的數據。舉個例子:

>>> L = [1, 2, 3]
>>> dict1 = {"list": L}
>>> tuple5 = (dict1.copy(),)
>>> print tuple5
({'list': [1, 2, 3]},)
>>> L[0] = "a"
>>> print L
['a', 2, 3]
>>> print tuple5
({'list': ['a', 2, 3]},)

如果想要一個深層次的拷貝結果,需要使用如下的方法

import copy
res_copy = copy.deepcopy(tuple5) #此方法將會進行深層次拷貝

 

好了,先寫到這吧,算是總結完了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM