我编写了一个Python程序来充当购物 list 或其他列表编辑器。它按原样显示列表,然后询问您是否要添加某些内容,然后询问您是否要查看列表的最新版本。这是代码:
#!/usr/bin/python
import sys
def read():
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
print(myList)
myList = []
f.close()
def add_to(str):
newstr = str + "\n"
f = open("test.txt","a") #opens file with name of "test.txt"
f.write(newstr)
f.close()
read()
yes = "yes"
answerone = raw_input("Would you like to add something to the shopping list?")
if answerone == yes:
answertwo = raw_input("Please enter an item to go on the list:")
add_to(bob)
answerthree = raw_input("Would you like to see your modified list?")
if answerthree == yes:
read()
else:
sys.exit()
else:
sys.exit()
当它显示列表时,它会以长度递增的列的形式显示它。 相反,它在文本文件中显示如下:
Shopping List
Soap
Washing Up Liquid
它显示如下:
['Shopping List\n']
['Shopping List\n', 'Soap\n']
['Shopping List\n', 'Soap\n', 'Washing Up Liquid\n']
我想知道是否有人可以帮助我理解为什么会这样,以及如何解决它。 仅供引用,我正在使用 python 2.6.1
编辑:感谢所有评论和回答的人。我现在尝试编辑代码以使其按字母顺序对列表进行排序,但它不起作用。我编写了一段测试代码来尝试使其工作(这将在 read() 函数中):
#!usr/bin/python
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
f.close()
print myList
subList = []
for i in range(1, len(myList)):
print myList[i]
subList.append(myList[i])
subList.sort()
print subList
这是文本文件:
Test List
ball
apple
cat
digger
elephant
这是输出:
Enigmatist:PYTHON lbligh$ python test.py
['Test List\n', 'ball\n', 'apple\n', 'cat\n', 'digger\n', 'elephant']
ball
apple
cat
digger
elephant
['apple\n', 'ball\n', 'cat\n', 'digger\n', 'elephant']
再一次,任何故障排除都会有所帮助。 谢谢
P.S 我现在使用 python 2.7.9
最佳答案
在读取中,您将在读取每一行后打印整个列表。您只需要打印当前行:
def read():
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
print(line)
myList = [] # also you are setting it to empty here
f.close()
此外,您应该使用 with
语句来确保文件关闭;并且没有理由使用 myList
因为您尚未返回任何更改;并且您希望从项目的开头和结尾中 strip()
额外的空格,因此最小值为:
def read():
with open('test.txt') as f:
for line in f:
line = line.strip()
print line # this is python 2 print statement
如果需要返回值:
def read():
my_list = []
with open('test.txt') as f:
for line in f:
line = line.strip()
my_list.append(line)
print line
return my_list
关于python - 列出程序不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28782227/