如何将存储为字符串的元组转换回元组后转换为字符串?

时间:2018-06-10 16:26:23

标签: python python-3.x tuples text-files

如果我将元组composer install --no-suggest 作为字符串存储在txt文件中,我怎样才能从txt文件中提取它并将其转换回原始元组?

4 个答案:

答案 0 :(得分:3)

也许你可以使用

s="(1, 2, 3)"
tuple(int(x) for x in s.strip('()').split(','))

删除'('和')',然后使用tuple()

感谢@bla指出可以使用s.strip('()')代替s.replace('(').replace(')')

答案 1 :(得分:0)

假设您的元组位于afisare(),那么您可以尝试使用void Joc::afisare(ostream &os) const { os << "Numele jocului:" << this->nume << ' ' << "Stoc:" << this->stoc << ' ' << "Descrierea joc: " << this->Descriere << ' '; for(list<string>::const_iterator it = upd.begin(); it != upd.end(); it++) { os << "Lista:" << *it << endl; } } void Joc::afisare() const { afisare(cout); } ostream& operator<<(ostream &os, const Joc &j) { os << endl; j.afisare(os); os << endl; return os; } 中编写的代码来读取文件中的元组。

»ReadTuple.py

MyTuple.txt

»MyTuple.txt enter image description here

最后,如果您使用ReadTuple.py运行上面的代码,那么您将能够在屏幕上看到读取元组及其类型。

»输出

# Open file in read mode
with open('MyTuple.json', encoding='utf-8') as f:
    content = f.read()
    t = eval(content);

# print tuple t read from file
print(t);

# print type of t
print(type(t));

答案 2 :(得分:0)

如果您的文件只包含元组,则只需使用eval

In [1]: with open('tuple.txt') as f:
   ...:     t = eval(f.read())
   ...:     

In [2]: t
Out[2]: (1, 2, 3)

请注意,eval 不应与不受信任的输入一起使用这意味着不要在用户可以输入的某些随机数据或您的程序从互联网上下载的随机数据上使用eval

假设tuple.txt引用元组,创建t并不是很难:

In [4]: with open('tuple.txt', 'w') as f:
   ...:     f.write(str(t))
   ...:

一般情况下,我建议您尽可能使用json模块 。这是一种非常通用的数据格式,人们也很容易阅读。后者对于生成测试数据和捕获错误是一件好事。

如果您有表格数据,那么sqlite3可能是个不错的选择。

答案 3 :(得分:0)

if __name__ == "__main__":
    # read it from a file
    with open("filename.txt", "r") as myfile:
        # loop through your text file line by line (if you have multiple of these)
        lines = []
        while True:
            # read a line from text
            line = myfile.readline()
            # add the line to a list
            lines.append(line)
            # if there are no more lines to read, step out of loop
            if not line:
                break
    # create a list of tuples
    list_of_tup = []
    for line in lines:
        # remove next line tag "\n"
        line = line[:-1]
        # use eval() to evaluate a string
        list_of_tup.append(eval(line))
相关问题