Hướng dẫn delete line in json file python - xóa dòng trong tệp json python

Đây là vấn đề mà, tôi có thể xóa các dòng khỏi thư mục của mình nhưng tôi không thể chọn chúng làm cách simillar của chúng.

Ví dụ: tôi đã có một tệp .json với 3000 dòng hoặc v.v. và tôi cần xóa các dòng bắt đầu bằng ví dụ "navig". Làm thế nào chúng ta có thể sửa đổi mã Python?

with open("yourfile.txt", "r") as f:
    lines = f.readlines()

with open("yourfile.txt", "w") as f:    
    for line in lines:
        if line.strip("\n") != "nickname_to_delete":
            f.write(line) 

(Mã được lấy từ một câu trả lời khác.)

Hướng dẫn delete line in json file python - xóa dòng trong tệp json python

Michael H.

3.0752 Huy hiệu vàng19 Huy hiệu bạc 30 Huy hiệu Đồng2 gold badges19 silver badges30 bronze badges

Đã hỏi ngày 27 tháng 12 năm 2019 lúc 10:41Dec 27, 2019 at 10:41

3

Bạn có thể làm điều gì đó như thế này:

with open("yourfile.txt", "r") as f:
    lines = f.readlines()

with open("yourfile.txt", "w") as f:    
    for line in lines:
        if not line.startswith(YOUR_SEARCH_STRING):
            f.write(line)

Hoặc nếu bạn chỉ muốn viết tệp một lần:

with open("yourfile.txt", "r") as f:
    lines = f.readlines()

lines_to_write = [line for line in lines if not line.startswith(YOUR_SEARCH_SRING)]

with open("yourfile.txt", "w") as f:    
    f.write(''.join(lines_to_write))

Đã trả lời ngày 27 tháng 12 năm 2019 lúc 10:47Dec 27, 2019 at 10:47

Michael H.Michael H.Michael H.

3.0752 Huy hiệu vàng19 Huy hiệu bạc 30 Huy hiệu Đồng2 gold badges19 silver badges30 bronze badges

0

Đã hỏi ngày 27 tháng 12 năm 2019 lúc 10:41

import json

with open('yourJsonFile', 'r') as jf:
    jsonFile = json.load(jf)

print('Length of JSON object before cleaning: ', len(jsonFile.keys()))

testJson = {}
keyList = jsonFile.keys()
for key in keyList:
    if not key.startswith('SOMETEXT'):
        print(key)
        testJson[key] = jsonFile[key]

print('Length of JSON object after cleaning: ', len(testJson.keys()))

with open('cleanedJson', 'w') as jf:
    json.dump(testJson, jf)

Bạn có thể làm điều gì đó như thế này:Dec 27, 2019 at 11:11

Hướng dẫn delete line in json file python - xóa dòng trong tệp json python

Hoặc nếu bạn chỉ muốn viết tệp một lần:Mousam Singh

Đã trả lời ngày 27 tháng 12 năm 2019 lúc 10:472 gold badges8 silver badges24 bronze badges

Xóa đối tượng JSON khỏi danh sách trong Python #

Để xóa đối tượng JSON khỏi danh sách:

  1. Phân tích đối tượng JSON vào một danh sách python từ điển.
  2. Sử dụng hàm
    with open("yourfile.txt", "r") as f:
        lines = f.readlines()
    
    with open("yourfile.txt", "w") as f:    
        for line in lines:
            if not line.startswith(YOUR_SEARCH_STRING):
                f.write(line)
    
    0 để lặp qua lần lặp qua danh sách.
  3. Kiểm tra xem mỗi từ điển có phải là phương pháp bạn muốn xóa và sử dụng phương thức
    with open("yourfile.txt", "r") as f:
        lines = f.readlines()
    
    with open("yourfile.txt", "w") as f:    
        for line in lines:
            if not line.startswith(YOUR_SEARCH_STRING):
                f.write(line)
    
    1 để loại bỏ dicting phù hợp không.

Copied!

import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_list = json.load(f) # 👇️ [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}] print(my_list) for idx, obj in enumerate(my_list): if obj['id'] == 2: my_list.pop(idx) new_file_name = 'new-file.json' with open(new_file_name, 'w', encoding='utf-8') as f: f.write(json.dumps(my_list, indent=2))

Ví dụ cho thấy cách xóa đối tượng JSON khỏi một mảng các đối tượng trong một tệp.

Bạn có thể sử dụng cùng một cách tiếp cận để xóa một đối tượng JSON khỏi một mảng các đối tượng bên ngoài tệp.

Copied!

import json my_json = '[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]' my_list = json.loads(my_json) for idx, dictionary in enumerate(my_list): if dictionary['id'] == 2: my_list.pop(idx) # 👇️ [{'id': 1, 'name': 'Alice'}] print(my_list) json_again = json.dumps(my_list) print(json_again) # 👉️ '[{"id": 1, "name": "Alice"}]'

Nếu JSON của bạn được đặt trong một tệp, hãy sử dụng phương thức

with open("yourfile.txt", "r") as f:
    lines = f.readlines()

with open("yourfile.txt", "w") as f:    
    for line in lines:
        if not line.startswith(YOUR_SEARCH_STRING):
            f.write(line)
2 để phân tích JSON.

Phương thức JSON.LOAD được sử dụng để giảm dần một tệp vào đối tượng Python, trong khi phương thức JSON.LOADS được sử dụng để giảm bớt chuỗi JSON thành đối tượng Python.

Bước tiếp theo là lặp lại trong danh sách và kiểm tra xem một khóa trong mỗi từ điển có một giá trị cụ thể.

Copied!

import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_list = json.load(f) # 👇️ [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}] print(my_list) for idx, obj in enumerate(my_list): if obj['id'] == 2: my_list.pop(idx) new_file_name = 'new-file.json' with open(new_file_name, 'w', encoding='utf-8') as f: f.write(json.dumps(my_list, indent=2))

Khi chúng tôi tìm thấy từ điển phù hợp, chúng tôi phải sử dụng phương thức

with open("yourfile.txt", "r") as f:
    lines = f.readlines()

with open("yourfile.txt", "w") as f:    
    for line in lines:
        if not line.startswith(YOUR_SEARCH_STRING):
            f.write(line)
3 để xóa nó khỏi danh sách.

Phương thức Danh sách.pop loại bỏ mục tại vị trí đã cho trong danh sách và trả về nó.

Bạn cũng có thể thêm câu lệnh

with open("yourfile.txt", "r") as f:
    lines = f.readlines()

with open("yourfile.txt", "w") as f:    
    for line in lines:
        if not line.startswith(YOUR_SEARCH_STRING):
            f.write(line)
4 nếu bạn chỉ muốn xóa từ điển
with open("yourfile.txt", "r") as f:
    lines = f.readlines()

with open("yourfile.txt", "w") as f:    
    for line in lines:
        if not line.startswith(YOUR_SEARCH_STRING):
            f.write(line)
5 khỏi danh sách.

Copied!

for idx, obj in enumerate(my_list): if obj['id'] == 2: my_list.pop(idx) break

Điều này giúp bạn tiết kiệm một thời gian trong các lần lặp không cần thiết nếu từ điển đến đầu danh sách.

Bước cuối cùng là mở một tệp mới (

with open("yourfile.txt", "r") as f:
    lines = f.readlines()

with open("yourfile.txt", "w") as f:    
    for line in lines:
        if not line.startswith(YOUR_SEARCH_STRING):
            f.write(line)
6) trong ví dụ, tuần tự hóa danh sách thành
with open("yourfile.txt", "r") as f:
    lines = f.readlines()

with open("yourfile.txt", "w") as f:    
    for line in lines:
        if not line.startswith(YOUR_SEARCH_STRING):
            f.write(line)
7 và viết nó vào tệp.

Copied!

new_file_name = 'new-file.json' with open(new_file_name, 'w', encoding='utf-8') as f: f.write(json.dumps(my_list, indent=2))

Làm cách nào để xóa một dòng cụ thể khỏi tệp JSON trong Python?

Xóa mục khỏi Json Python Code Ví dụ - codegrepper.com Nhập json obj = json.Load (Open ("Tệp.pop (i) Break # xuất tệp được cập nhật với JSON Open khá ...Iterate through the objects in the JSON and pop (remove) # the obj once we find it. pop(i) break # Output the updated file with pretty JSON open ...

Làm thế nào để bạn xóa một dòng từ một tệp trong Python?

Sử dụng DEL để xóa một dòng từ một tệp trong đó vị trí của nó được biết {#use-del) Mở tệp để đọc và sử dụng tệp.Readlines () để tạo một danh sách trong đó mỗi phần tử là một dòng từ tệp.Sử dụng danh sách cú pháp del [index] với danh sách làm danh sách các dòng để xóa phần tử tại chỉ mục. {#use-del) Open the file for reading and use file. readlines() to create a list where each element is a line from the file. Use the syntax del list[index] with list as the list of lines to delete the element at index .

Làm cách nào để xóa nội dung của tệp JSON?

Bạn có thể chỉ cần cắt tệp hoặc ghi đè lên nó bằng "{}".Lưu câu trả lời này.