zoukankan      html  css  js  c++  java
  • [Python] Read and Parse Files in Python

    This lesson will teach you how to read the contents of an external file from Python. You will also learn how to use the python csv module to read and parse csv data, as well as the json module to read and parse json data.

    # f = open('animals.csv')
    
    # for line in f:
    #     print(line)
    
    # f.close()
    
    # with open('animals.csv', 'r') as f:
    #     print(f.read())
        
    # import csv
    # with open('animals.csv', 'r') as f:
    #     animals = csv.reader(f)
    #     for row in animals:
    #         if row[-1] == 'True':
    #             print("{0} is a {1} and is housebroken".format(row[0], row[1]))
    #         elif row[-1] == 'False':
    #             print("{0} is a {1} and is not housebroken!".format(row[0], row[1]))
    
    # import json
    # with open('animals.json', 'r') as r:
    #     data = json.load(r)
    #     for row in data:
    #         print(row['name'])
    
    # f = open('cars.txt', 'a')
    # cars = ['chevy', 'tesla', 'ford']
    # for car in cars:
    #     f.write(car + '
    ')
    
    # f.close()
    
    # with open('cars.txt', 'a') as f:
    #     cars = ['chevy', 'vw', 'mazda']
    #     for car in cars:
    #         f.write(car + '
    ')
    
    cars = [
        {"make": "chevy"},
        {"make": "tesla"},
        {"make": "porsche"}
    ]
    import json
    with open('cars.json', 'w') as f:
        json.dump(cars, f)
  • 相关阅读:
    pat1111-1120
    pat1101-1110
    pat1091-1100
    pat1081-1090
    pat1071-1080
    pat1061-1070
    2017华为软件精英挑战赛总结
    pat1051-1060
    【转】WPF中PasswordBox控件的Password属性的数据绑定
    Python学习-41.Python中的断言
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8033310.html
Copyright © 2011-2022 走看看