Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将数字文件读入元组?_Python - Fatal编程技术网

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

在python中将数字文件读入元组?,python,Python,我有一个文件,里面有这样的数字: 5 10 15 20 我知道如何编写读取文件并将数字输入列表的代码,但如果元组不支持append函数,如何编写读取文件并将数字输入元组的代码?到目前为止,我得到的是: filename=input("Please enter the filename or path") file=open(filename, 'r') filecontents=file.readlines() tuple1=tuple(filecontents) print(tuple

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

5

10

15

20
我知道如何编写读取文件并将数字输入列表的代码,但如果元组不支持append函数,如何编写读取文件并将数字输入元组的代码?到目前为止,我得到的是:

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

('5\n', '10\n', '15\n', '20\n')
应该是这样的:

5,10,15,20

如果您已经知道如何创建
int
s的
列表
,只需将其转换为
元组
,就像您在尝试解决问题时所做的那样

在这里,
映射
对象也可以转换为元组,但它也可以与
列表
一起使用:

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

print(filecontents)
另外,如果将
语句一起使用,则无需担心关闭文件(代码中也缺少该部分)

尝试以下操作:

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)
建议在打开(..)时使用
,以确保文件在使用完毕后关闭。然后使用表达式将返回的列表转换为元组

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,filter(None,open(my_file,“rb”))您的文件中是否实际有额外的换行符(因此它只在每2行上获得一个值),或者这是它如何针对问题进行格式化的结果?请,精心设计。我真的不明白这种方法有什么不对Happy now@U9 Forward?很高兴知道,很难过那个人没有评论原因:/Okay修复了你的打字错误:-)Good point@JoranBeasley,将我的解决方案改为使用
split()
,而不是
splitlines()
,尽管用户的输出是“5,10,15,20”他要问的是如何使它成为一个元组,这是你的代码无法实现的。。。