Python learning summary (2) csv newline uuid

1 csv file reading and writing

class Test(object):
    # 读取 两种方法
    def read(self):
        with(open("ccc.csv", "r")) as f:
            reader = csv.reader(f)
            next(reader)  # 是为了从数据开始读 第一行是key 值
            for x in reader:
                print(x)

    def read2(self):
        with open("ccc.csv", 'r') as f:
            reader = csv.DictReader(f)  # 读取成一个字典的 形式

    header = ["name", "age", "height"]
    rows = [
        ("张珊", 12, 160),
        ("李四", 12, 160),
        ("王五", 12, 160)
    ]

    def write(self):
        with open('CCC.csv', 'w', encoding='utf-8', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(self.header)
            writer.writerows(self.rows)
    row_dict=[
        {'name':"张珊",'age':12,'height':170},
        {'name':"张珊",'age':12,'height':170},
        {'name':"张珊",'age':12,'height':170},
    ]
    def write2(self):
        with open("csc.csv",'w',encoding="utf-8",newline='') as f:
            write=csv.DictWriter(f,self.header)
            write.writeheader()
            write.writerows(self.row_dict)
if __name__ == '__main__':
    test=Test()
    test.write2()

Summary
1 When writing, there will be an extra blank line for no reason. That is because a \n will be automatically added when opening, and newline="" will be enough when opening.
2 When writing, use a dictionary to write in csv.DicWriter (f,self.header) Pass in the key value list of dict
3 When writing, remember to add write.writeheader(), it will not be automatically written to the table header, use this method to write

2. Use uuid to produce a unique ID.
Note that there are four methods without uuid2()
uuid.uuid1(), based on timestamp and MAC address
uuid, uuid3(uuid.NAMESPACE_DNS, name), based on the MD5 hash value of the name, you can Guarantee the uniqueness of different names in the same namespace and the uniqueness of different namespaces, but the UUID generated by the same name in the same namespace is the same. uuid.uuid4(
), randomly generated, with a small probability of duplication
uuid.uuid5(uuid. NAMESPACE_DNS, name) and uuid3 similar to name-based SHA-1 hashes

import uuid

uid1 =uuid.uuid1()
name="space"
namespace=uuid.NAMESPACE_DNS
uid3=uuid.uuid3(namespace,name)
uid4 =uuid.uuid4()
uid5=uuid.uuid5(namespace,name)

Guess you like

Origin blog.csdn.net/m_cainiaokuaifei/article/details/92799194