Python文件,向列表中添加值/从列表中添加值
我正在尝试将文件中的值添加到列表中,然后能够将文件中的值添加到列表中。 这就是我所拥有的:Python文件,向列表中添加值/从列表中添加值,python,list,file,python-3.x,user-input,Python,List,File,Python 3.x,User Input,我正在尝试将文件中的值添加到列表中,然后能够将文件中的值添加到列表中。 这就是我所拥有的: L = [] def readFile(L): ui = input("Please enter your file name:") r = open(ui, 'r') files = r.readlines() for line in files: return float(line) L.append(line) r.cl
L = []
def readFile(L):
ui = input("Please enter your file name:")
r = open(ui, 'r')
files = r.readlines()
for line in files:
return float(line)
L.append(line)
r.close()
def fileAddValue(L):
ui = input("Please enter your file name:")
val = float(input("Enter the value you would like to add to the list: "))
r = open(ui, 'a')
file = r.write(str(val) + '\n')
for ix in r:
x = float(ix)
L.append(x)
L.sort()
r.close()
你需要那样的东西吗
L = []
def readFile():
ui = input("Please enter your file name:")
r = open(ui, 'r')
files = r.readlines()
for line in files:
value = float(line)
L.append(value)
r.close()
def fileAddValue():
ui = input("Please enter your file name:")
val = float(input("Enter the value you would like to add to the list: "))
r = open(ui, 'a+')
r.write(str(val) + '\n')
for ix in r:
x = float(ix)
L.append(x)
L.append(val)
L.sort()
r.close()
if __name__ == '__main__':
readFile()
fileAddValue()
print(L)
虽然它不是pytonic(除非必要,否则尽量不要碰你的代码),但如果我答对了你的问题,它就会起作用。
缩进代码在Python中很重要,从函数返回可以保证返回后的代码永远不会运行。如果您想要一个“返回”多个值的函数,以便可以使用
for
对该“函数”进行迭代,请使用yield
而不是return
,您有一些问题
首先,当您打开需要与一起使用的文件时,这将为您关闭文件
现在,当你依次阅读每一行时,你将返回第一行。这是从整个函数返回的,因此不是您想要的。我认为你想把每一项都加到你的清单上
此外,您的函数更通用。传入文件名和数据。将它们置于功能之外,以获得更大的灵活性
现在还不清楚你想在这里做什么。我假设您希望指定要添加到文件中持久化的列表中的值。有更好的方法可以做到这一点。这是我根据您的原始代码进行的尝试
def readFile(ui):
L = []
with open(ui, 'r') as f:
for line in f.readlines():
L.append(float(line))
return sorted(L)
def fileAddValue(ui, val):
with open(ui, 'a') as f:
f.write(str(val) + '\n')
ui = raw_input("Please enter your file name:")
L = readFile(ui)
print('original file:')
print(L)
val = float(raw_input("Enter the value you would like to add to the list: "))
fileAddValue(ui, val)
L = readFile(ui)
print('updated file:')
print(L)
你的问题是什么?对不起,我不清楚。我只是想弄清楚如何从文件中读取值,并将它们存储在列表和数据中。我一个接一个地出错。对不起,我不清楚。谢谢你的帮助,这很有帮助!我只是想弄清楚如何从文件中读取值,并将它们存储在列表和数据中。我不断地犯错误。