Запись двухмерного списка в файл, чтение и повторное использование сохраненного списка

Попробуйте этот скриптовый инструмент TamperMonkey

Чтобы переопределить переполнение

body {
   overflow: visible !important;
}

Сценарий, который будет работать с TamperMonkey:

// ==UserScript==
// @name         InvestingRemoveScrollBodyBlocker
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  Remove body overflow hidden
// @author       Ángel Guzmán Maeso 
// @match        https://*.investing.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    // Credits: https://stackoverflow.com/questions/51330252/how-to-remove-the-css-rule-body-overflowhidden-automatically
    document.body.style.cssText = "visible !important";
})();

1
задан Vasilis G. 18 January 2019 в 18:50
поделиться

3 ответа

json хорош для сериализации списков / диктов / чисел / строк:

import json 

My_list = [['Hello', 'World', 0], ['Pretty', 'World', 1], ['Tired', 'World', 2]]

#write to file
with open("data.json", "w") as file:
    json.dump(My_list, file)

#read from file
with open("data.json") as file:
    new_list = json.load(file)

print(new_list)

Результат:

[['Hello', 'World', 0], ['Pretty', 'World', 1], ['Tired', 'World', 2]]
0
ответ дан Kevin 18 January 2019 в 18:50
поделиться

Привет всем, кто заинтересован.

Я хотел сохранить массив в текстовый файл Python и извлечь его полностью, чтобы я мог обратиться ко всем элементам.

Я продолжил свою проблему и решил ее с помощью очень грязного кода, я уверен.

Код ниже делает то, что я хотел сделать.

Бессмысленное упражнение, но я просто должен был это сделать.

Спасибо за вашу помощь и идеи.

my_list = []
my_list_669 = []

def create_list():
    #Creating the list

    for x in range(5):
        my_list.append(["Hello", "World", x])

    print("my_list = ", my_list)


def save_list_to_file():
    #creating the string

    string_1 = ""

    for item in my_list:
        string = item[0] + "," + item[1] + "," + str(item[2]) + "\n"
        string_1 += string
        #adds records to a string with a line return after each record

    with open('your_file.txt', 'w') as f:
            f.write(string_1)


def recover_list():

    with open('your_file.txt', 'r') as f:
            tiing = f.read().splitlines()
            #splits lines at \n and inserts into array called 'tiing'
            #each item is equivalent to a record

    for items1 in tiing:
        my_list_69 = items1.split(",")
        #splits the array items in ting at "," mark
        #these are now in an array called 'my_list_69'
        #below I access all items from within the list
        #and append them to a temporary sub-list

        sub_list = []
        for items in my_list_69:
            sub_list.append(items)

        my_list_669.append(sub_list)  this reconstructs the list


create_list()
save_list_to_file()
recover_list()

Testing:
print(my_list_669)
print(my_list_669[0])
print(my_list_669[0][2])
for items in my_list_669:
    print(items)
0
ответ дан Loosa Bway 18 January 2019 в 18:50
поделиться

Примите во внимание также yaml . Требуется установить pyyaml ​​ (pip install pyyaml).

import yaml

Сохранить объект списка в файл:

my_list = [['Hello', 'World', 0], ['Pretty', 'World', 1], ['Tired', 'World', 2]]

with open('my_list.yml', 'w') as outfile:
    yaml.dump(my_list, outfile, default_flow_style=False)

Выходной файл выглядит следующим образом:

- - Hello
  - World
  - 0
- - Pretty
  - World
  - 1
- - Tired
  - World
  - 2

Чтобы загрузить список обратно:

with open("my_list.yml", 'r') as inputfile:
    my_list_back = yaml.load(inputfile)


Для прямой обработки строки вы можете использовать стандартную библиотеку ast.literal_eval , это простой пример, который вы можете настроить далее.

import ast

string_list = (str(my_list)) # convert tostring then save it to file
print(string_list.__class__) # it's a string
reconverted_list = ast.literal_eval(string_list) # convert back with ast
print(reconverted_list.__class__) # it's a list

Чем базовое чтение / запись может быть:

with open('my_list.txt', 'w') as file:
    file.write(str(my_list))

with open('my_list.txt', 'r') as file:
    my_list_back = ast.literal_eval(file.read())
0
ответ дан iGian 18 January 2019 в 18:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: