简体   繁体   English

将文件中的列表保存为 int 并且读取时为什么它是字符串?

[英]Saving list in file as int and when reading why is it in string?

I am saving a integer list to file with我正在保存一个 integer 列表来归档

 number = [3808640804, 552553035, 815157969, 1623809649, 1851153805, 4058081409, 2438887622, 2833416221, 1727496343, 3172042750] txt = f"H:\data_set\\testing\\1K\chunk.txt" with open(txt, 'w', encoding='utf-8', errors='ignore') as filee: for line in number: filee.write(f"{line}\n")

But When I read the file using script但是当我使用脚本读取文件时

 txt = f"H:\data_set\\testing\\1K\chunk.txt" with open(txt, 'r', encoding='utf-8', errors='ignore', buffering=100000) as filee: g = filee.readlines() print(type(g[1])) print(g[0:10])
I get this output: 我得到这个 output:

 <class 'str'> ['3808640804\n', '552553035\n', '815157969\n', '1623809649\n', '1851153805\n', '4058081409\n', '2438887622\n', '2833416221\n', '1727496343\n', '3172042750\n']

Whereas I should get this output:而我应该得到这个 output:

 [3808640804, 552553035, 815157969, 1623809649, 1851153805, 4058081409, 2438887622, 2833416221, 1727496343, 3172042750]

Can you try reading the file with this code:您可以尝试使用以下代码读取文件吗:

with open(txt, 'r') as filee:
numbers = [int(line.strip()) for line in filee]
print(numbers)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM