Python Learning Journey -10-file storage: TXT file, CSV file, JSON file

Source: Internet
Author: User
Tags convert string to json string to json


1. Store the data txt file. 1.1 Examples:
# 1 Store txt file

data = ‘‘ ‘I ’m a txt file’ ‘‘
# Stored file name: file = ‘test.txt’
# File opening method: mode = ‘a’
# Encoding format: encoding = ‘UTF-8’
with open (file = ‘test.txt’, mode = ‘a’, encoding = ‘UTF-8’) as f:
     f.write (data) # save content
     f.close () # Close the file
1.2 Different modes of open files:
Mode Description
R R to open the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
Rb RB, opens a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode.
r+ r+, open a file for read-write. The file pointer will be placed at the beginning of the file.
rb+ rb+, open a file in binary format for read-write. The file pointer will be placed at the beginning of the file.
W W, open a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file.
Wb WB, opens a file in binary format only for writing. Overwrite the file if it already exists. If the file does not exist, create a new file.
w+ w+, open a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.
wb+ wb+, open a file in binary format for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.
A A, open a file for append. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to. AB opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to.
A + A +, open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file opens with an append mode. If the file does not exist, create a new file to read and write.
ab+ ab+, open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file to read and write.
2. Store CSV file 2.1 instance one: Store a row of files
import csv # import csv module

# Example 1: Store a line of files

info_1 = [‘name’, ‘age’, ‘sex’]
info_2 = [‘Pharaoh’, ‘30’, ‘male’]

# Stored file name: ‘test_info.csv’
# File opening method: ‘a’
# Encoding format: encoding = ‘ANSI’. Setting the encoding format to ANSI can avoid garbled characters in Excel software.
# newline = ‘‘, if this parameter is not set, a space will appear between two adjacent lines.
with open (‘test_info.csv’, ‘a’, encoding = ‘ANSI’, newline = ‘‘) as f:
     writer = csv.writer (f) # call the writer () method of the csv library to initialize the write object
     writer.writerow (info_1) # save the first line of data
     writer.writerow (info_2) # save the second line of data
Output content:Age
name Sex
Lao Wang 30 Man
2.2 Example two: storing data in the form of a dictionary
import csv # import csv module

# Example 2: Store data in dictionary form

info = {
     ‘Name’: ‘Pharaoh’,
     ‘Age’: ‘30’,
     ‘Sex’: ‘Men’,}

with open (‘test_info_2.csv’, ’a’, encoding = ‘ANSI’, newline = ‘‘) as f:
     fieldnames = [‘name’, ‘age’, ‘sex’] # Set the file header
     writer = csv.DictWriter (f, fieldnames = fieldnames) # use the DictWriter () method to initialize the writer
     writer.writeheader () # first write the file header
     writer.writerow (info) # Store the main content of the file
2.3 Example three: storing data in multiple dictionary forms
import csv # import csv module

# Example 3: Store data in multiple dictionaries

info = [{‘name’: ‘Pharaoh’, ‘age’: ‘30’, ‘sex’: ‘male’,},
         {‘Name’: ‘Boss’, ‘age’: ‘1’, ‘sex’: ‘male’,},
         {‘Name’: ‘Old 2’, ‘age’: ‘2’, ‘sex’: ‘female’},
         {‘Name’: ‘Old 3’, ‘age’: ‘3’, ‘sex’: ‘Male’}]

with open (‘test_info_2.csv’, ’a’, encoding = ‘ANSI’, newline = ‘‘) as f:
     fieldnames = [‘name’, ‘age’, ‘sex’] # Set the file header
     writer = csv.DictWriter (f, fieldnames = fieldnames) # use the DictWriter () method to initialize the writer
     writer.writeheader () # first write the file header
     writer.writerows (info) # Store the main content of the file
    
     # Note: The last place to store the main file is: the writerows () method, which is one more s than storing a single file.
Output content:Age
name Sex
Lao Wang 30 Man
Boss 1 Man
Old 2 2 Woman
Old 3 3 Man
3. Storing JSON files
    • Json, all called JavaScript Object Notation, is the JavaScript objects tag, which represents data through the combination of objects and arrays, is simple to construct but highly structured, and is a lightweight data interchange format.
3.1 Conversion of Json files:
    • The loads () method converts a JSON text string to a JSON object.
    • The dumps () method converts a Json object to a text string.
Instance:
import json # import json module

info = ‘‘ ‘‘ [
         {"name": "Lao Wang", "age": "30", "sex": "Male"},
         {"name": "Boss", "age": "1", "sex": "Male"}
         ] ‘‘ ‘

print (type (info)) # First print and see the type of info
# Output: <class ‘str’>

# 1. Convert string to json file

info_1 = json.loads (info) # convert string to json file
print (type (info_1)) # print the type of the new file info_1
print (info_1) # print info_1
# Output: <class ‘list’>
# Output: [{'name': 'Lao Wang', 'age': '30', 'sex': 'Male'}, {'name': 'Boss',' age ':' 1 ',' sex ':' Male '}]


# 2. Convert json file to string

info_2 = json.dumps (info_1) # convert string to json file
print (type (info_2)) # print the type of new file info_2
# Output: <class ‘str’>
3.2 Saving and reading JSON files
import json # import json module

info = ‘‘ ‘‘ [
         {"name": "Lao Wang", "age": "30", "sex": "Male"},
         {"name": "Boss", "age": "1", "sex": "Male"}
         ] ‘‘ ‘

# 1. Output as json file
with open (‘test_json.json’, ‘w’) as f:
     f.write (json.dumps (info)) #Use the dumps () method to convert the json object into a string, and then use the write () method to write the file

# 2. Read json file
with open (‘test_json.json’, ‘r’) as f:
     str = f.read ()
     data = json.loads (str) #Use the loads () method to convert the string and print it out
     print (data) 
Note: The Json string data represents the need to use double quotes and cannot use single quotes, otherwise the loads () method fails to parse.


Python Learning Journey -10-file storage: TXT file, CSV file, JSON file


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.