我目前正在创建一个数据库API,以便更好地掌握API的工作原理。目前修复错误和什么,当我尝试delete
函数(选项3)时,它给了我一个错误,并告诉我split
函数返回一个值而不是两个。
我的猜测是,它要么不正确地读取行,要么通过读取文本文件,它不注册制表符('t'
),而是作为一个空格(' '
)。
我是通过VS Code来做这个的,不确定这是否是缩进和其他东西的一个贡献因素。但是我把它设置为4个空格= tab,就像Python IDLE通常做的那样。
代码如下:
import time
def add(filename):
print('Name?')
key = input()
print('Phone number?')
value = input()
f = open(filename, "a")
f.write(key + "t" + value + "n")
f.close()
def find(filename, key):
f = open(filename, "r")
for line in f:
#first stores the current key in variable
(currentKey, currentValue) = line.split('t', 1)
if currentKey == key:
return currentValue[:-1]
f.close()
def delete(filename, key):
f = open(filename, "r")
f1 = open('temporary.txt', "w")
for (line) in f:
#Error occurs here
(currentKey, currentValue) = line.split('t', 1)
if currentKey != key:
f1.write(line)
f.close()
f1.close()
import os
os.replace('temporary.txt', filename)
def update(filename, key, value):
resultfile = "temporary.txt"
f = open(filename, "r")
f1 = open(resultfile, "w")
for line in filename:
(currentKey, currentValue) = line.split('t', 1)
if currentKey != key:
f1.write(line)
else:
f1.write(currentKey + 't' + value + 'n')
f.close()
f1.close()
import os
os.replace(resultfile, filename)
filename = 'telephone.txt'
#Current Menu Interface
def menu():
print("Welcome to the telephone directory")
print("Your options are:")
print()
print("1) Adding")
print("2) Finding")
print("3) Deleting")
print("4) Updating")
print("5) Quitting")
choice = input()
return choice
#actual decision code
def decision(choice):
loop = 1
while loop == 1:
if choice == '1':
add(filename)
choice = menu()
elif choice == '2':
print("What is the name of the person you are looking for?")
key = input()
value = find(filename, key)
print(key + "'s phone number is: " + value)
choice = menu()
elif choice == '3':
print("What is the name of the person you are looking to delete from the directory?")
key = input()
delete(filename, key)
choice = menu()
elif choice == '4':
print("What is the name of the person?")
key = input()
print("What is the telephone number you want to replace it with?")
value = input()
update(filename, key, value)
choice = menu()
elif choice == '5':
print("Thank you for using the program! Your file contents are stored in a file called 'telephone.txt'.")
time.sleep(1)
loop = 0
else:
print("Please enter a value from 1 to 5. No spaces at all.")
choice = menu()
choice = menu()
decision(choice)
您正在迭代字符串filename
,而不是文件句柄:
def delete(filename, key):
f = open(filename, "r")
f1 = open('temporary.txt', "w")
for (line) in filename: # here
...
这意味着您将获得filename
中的每个字符。所以如果filename
是'hello.txt'
,你会得到:
h
e
l
l
o
.
t
x
t
你应该做
f = open(filename)
for line in f:
# rest of loop
或者说:
with open(filename) as f:
for line in f:
# rest of loop
最后,如果行不包含制表符,str.split('t')
将返回一个单元素列表,因此您可以这样做:
try:
a, b = line.split('t', 1)
except ValueError:
print('No tab in line')
continue # skip the line
或者,如果您希望程序停止,您可以使用raise
try:
a, b = line.split('t', 1)
except ValueError:
print('No tab in line')
raise # stop the program
最后,处理制表符或空格的最好方法是@RufusVS建议的方法:
try:
a, b = line.split(None, 1)
except ValueError:
# either raise or continue
print('Line doesn't contain a whitespace separator')
continue
当str.split
被传递给None
时,因为函数需要一个分隔符参数,省略它会引发错误:
x = 'abc def'
x.split(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be str or None, not int
x.split(None, 1)
['abc', 'def']