python - 当我只需要向用户添加的行时,为什么它会在 nlist 中记录额外的项目/行( ' ' )?

标签 python list file

示例:我输入正数: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/

相关文章:

c# - 打开前检查文件是否已被使用(网盘,C#)

python - NameError:名称 'now' 未定义

C# Override List<T> 添加方法来检查列表是否为空

string - 在 Fortran 中获取可变长度字符串列表的更好方法

java - 计算两个列表之间的重复值时如何短路?

php - 如何使用 CURL 下载文件并将其保存到本地路径

java - Dijkstra 算法的文件输入

python - 使用 python gnupg,我的私钥被作为公钥读入

python - python中有没有一个命令可以让你重新执行刚刚执行过的函数?

python - python 样式结构的 BNF 语法