在 python 中将数字文件读入元组?



我有一个文件,里面有这样的数字:

5
10
15
20

我知道如何编写读取文件并将数字输入 LIST 的代码,但如果元组不支持追加函数,我如何编写读取文件并在 TUPLE 中输入数字的代码? 这是我到目前为止得到的:

filename=input("Please enter the filename or path")
file=open(filename, 'r')
filecontents=file.readlines()
tuple1=tuple(filecontents)
print(tuple1)

输出是这样的:

('5n', '10n', '15n', '20n')

应该是这样的:

5,10,15,20

试试这个:

s=','.join(map(str.rstrip,file))

演示:

filename=input("Please enter the filename or path: ")
file=open(filename, 'r')
s=tuple(map(str.rstrip,file))
print(s)

示例输出:

Please enter the filename or path: thefile.txt
(5,10,15,20)

建议使用with open(..)来确保文件在完成后关闭。然后使用表达式将返回的列表转换为元组。

filename=input("Please enter the filename or path")
with open(filename, 'r') as f:
lines = f.readlines()
tup = tuple(line.rstrip('n') for line in lines)
print(tup)

如果您确定它们是整数,则可以执行以下操作:

filename=input("Please enter the filename or path")
with open(filename, 'r') as f:
lines = f.readlines()
result = tuple(int(line.strip('n')) for line in lines)
print(resultt)

此外,如果您有列表,则始终可以将其转换为元组:

t = tuple([1,2,3,4])

因此,您可以构建附加元素的列表,并最终将其转换为元组

> 如果您已经知道如何对int进行list,只需将其转换为tuple,就像您在尝试解决问题时所做的那样。

在这里,map对象也可以 se 转换为元组,但它也适用于list

filename=input("Please enter the filename or path: ")
with open(filename, 'r') as file:
filecontents=tuple(map(int, file.read().split()))
print(filecontents)

此外,如果您使用with语句,则无需担心关闭文件(代码中也缺少该部分(

最新更新