示例:我输入正数:1、2、3、4,然后输入 -1 结束第一个函数。第二个函数中显示的列表(nlist)为['1', '2', '3', '4', '']。这个额外的第五项从哪里来?我该如何防止它?
def pos_num():
# Open num.txt and define num
num_list = open('num.txt', 'w')
num = 1
# While num is positive, ask user for input
while num >= 0:
num = int(input('Type + number to add to num_list, - number to end: '))
# If user input is positive: \
# convert to str, add to list, convert to int to continue loop
if num >= 0:
num = str(num)
num_list.write(num + '\n')
num = int(num)
# If user input is negative: \
# close num.txt and inform user
else:
num_list.close()
print('List has been written to num.txt')
# Call program 1
pos_num()
# Program 2: Number File Reader
def nfread():
# Ask user for filename to open
filename = input('Filename: ')
infile = open(filename, 'r')
# Create empty list
nlist = []
# Read first line, strip '\n', append to nlist, begin line count
line = infile.readline()
line = line.rstrip('\n')
nlist.append(line)
count = 1
# While line is not empty: \
# read line, strip '\n', append line to nlist, add 1 to count
while line != '':
line = infile.readline()
line = line.rstrip('\n')
nlist.append(line)
count += 1
print(line, count)
# Close num.txt
infile.close()
# Return nlist
return nlist
最佳答案
考虑更改此 block :
# Read first line, strip '\n', append to nlist, begin line count
line = infile.readline()
line = line.rstrip('\n')
nlist.append(line)
count = 1
# While line is not empty: \
# read line, strip '\n', append line to nlist, add 1 to count
while line != '':
line = infile.readline()
line = line.rstrip('\n')
nlist.append(line)
count += 1
print(line, count)
类似的事情
count = 0
for line in infile:
line = line.rstrip()
if line:
nlist.append(line)
count += 1
print(line, count)
在所有更改中,应该修复您的程序的更改是添加 if line:
——它将导致您的程序不向您的程序附加一个空元素。列表(仅对换行符调用 .rstrip()
的结果)。
关于python - 当我只需要向用户添加的行时,为什么它会在 nlist 中记录额外的项目/行( ' ' )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53051452/