【问题标题】:Reading a file in python, without skipping the first number在python中读取文件,而不跳过第一个数字
【发布时间】:2017-07-30 03:43:59
【问题描述】:

我需要用 Python 编写一个程序,它查看单独文本文件中的数字列表,并执行以下操作:显示文件中的所有数字,添加所有数字的总和,告诉我如何文件中有很多数字。 我的问题是它跳过了文件中的第一个数字

这是写入文件的程序的代码,如果有帮助的话:

import random

amount = int (input ('How many random numbers do you want in the file? '))
infile = open ('random_numbers.txt', 'w')
for x in range (amount):
    numbers = random.randint (1, 500)
    infile.write (str (numbers) + '\n')
infile.close()

这是我读取文件中数字的代码:

amount = 0
total = 0
infile = open ('random_numbers.txt', 'r')
numbers = (infile.readline())
try:

    while numbers:
        numbers = (infile.readline())
        numbers = numbers.strip('\n')
        numbers = int (numbers)
        print (numbers)
        total += numbers
        amount += 1

except ValueError:
    pass
print ('')
print ('')
amount +=1
print ('Your total is: ' ,total)
print ('The amount of numbers in file is: ', amount) 

现在我的问题是它跳过了文件中的第一个数字。我首先注意到它没有给我正确的数字数量,因此附加语句将额外的 1 添加到数量变量。但后来我再次测试,发现它跳过了文件中的第一个数字。

【问题讨论】:

  • 这可能是因为在写入文件时您在行尾添加了'\n',现在在阅读时您将'\n' 转换为int 这是不可能的跨度>
  • @ksai 我很确定这实际上是正确的。我试图从中剥离 \n,但无济于事。

标签: python readfile writefile


【解决方案1】:

怎么样:

with open('random_numbers.txt', 'r') as f:
    numbers = map(lambda x: int(x.rstrip()), f.readlines())

这会从字符串中的行中删除任何尾随换行符,然后将其转换为 int。完成后它还会关闭文件。

我不确定你为什么要计算它循环了多少次,但如果这是你想做的,你可以这样做:

numbers = list()
with open('random_numbers.txt', 'r') as f:
    counter = 0
    for line in f.readlines():
        try:
            numbers.append(int(line.rstrip()))
        except ValueError: # Just in case line can't be converted to int
            pass
        counter += 1

不过,我只会将len(numbers) 与第一种方法的结果一起使用。

正如 ksai 所提到的,ValueError 即将出现,很可能是因为行尾的 \n。我添加了一个使用 try/except 捕获 ValueError 的示例,以防它遇到由于某种原因无法转换为数字的行。

这是在我的 shell 中成功运行的代码:

In [48]: import random
    ...: 
    ...: amount = int (input ('How many random numbers do you want in the file? 
    ...: '))
    ...: infile = open ('random_numbers.txt', 'w')
    ...: for x in range (amount):
    ...:     numbers = random.randint (1, 500)
    ...:     infile.write (str (numbers) + '\n')
    ...: infile.close()
    ...: 
How many random numbers do you want in the file? 5

In [49]: with open('random_numbers.txt', 'r') as f:
    ...:     numbers = f.readlines()
    ...:     numbers = map(lambda x: int(x.rstrip()), numbers)
    ...:     

In [50]: numbers
Out[50]: <map at 0x7f65f996b4e0>

In [51]: list(numbers)
Out[51]: [390, 363, 117, 441, 323]

【讨论】:

    【解决方案2】:

    假设在您生成这些数字的代码中,“random_numbers.txt”的内容是由换行符分隔的整数:

    with open('random_numbers.txt', 'r') as f:
        numbers = [int(line) for line in f.readlines()]
        total = sum(numbers)
        numOfNums = len(numbers)
    

    'numbers' 包含列表中文件中的所有数字。如果你不想要方括号,你可以打印这个或 print(','.join(map(str,numbers)))。

    'total' 是它们的总和

    'numOfNums' 是文件中有多少个数字。

    【讨论】:

      【解决方案3】:

      最终对我有用的是:

      amount = 0
      total = 0
      infile = open ('random_numbers.txt', 'r')
      numbers = (infile.readline())
      try:
      
          while numbers:
              numbers = (infile.readline())
              numbers = numbers.strip('\n')
              numbers = int (numbers)
              print (numbers)
              total += numbers
              amount += 1
      
      except ValueError:
          pass
      print ('')
      print ('')
      amount +=1
      print ('Your total is: ' ,total)
      print ('The amount of numbers in file is: ', amount)
      

      Cory 关于添加 try and except 的提示是我认为最终成功的方法。

      【讨论】:

      • 没关系,现在它遇到了跳过文件中第一个数字的问题
      • 它跳过了第一个数字,因为您会立即在 while 语句的第一行覆盖它。我还将try/except 放在while 循环中,这样它就不会停在第一条坏线上。
      • 我将如何绕过覆盖它?
      • 完成工作后将numbers = (infile.readline()) 移至循环末尾。是的,我刚刚用你的代码进行了测试,它运行良好。
      • 谢谢!巨大的帮助人。希望我也可以将所有这些用于我正在编写的其他程序。
      【解决方案4】:

      如果是我,我想这样编码:

      from random import randint
      
      fname = 'random_numbers.txt'
      amount = int(input('How many random numbers do you want in the file? '))
      with open(fname, 'w') as f:
          f.write('\n'.join([str(randint(1, 500)) for _ in range(amount)]))
      
      with open(fname) as f:
          s = f.read().strip()    
      numbers = [int(i) for i in s.split('\n') if i.isdigit()]
      print(numbers)
      

      或者这样(需要pip install numpy):

      import numpy as np
      from random import randint
      
      fname = 'random_numbers.txt'
      amount = int(input('How many random numbers do you want in the file? '))
      np.array([randint(1, 500) for _ in range(amount)]).tofile(fname)
      
      numbers = np.fromfile(fname, dtype='int').tolist()
      print(numbers)
      

      【讨论】:

        【解决方案5】:

        我认为问题在于你如何放置代码,因为你无意中跳过了第一行,而另一个调用 infile.readline()

        amount = 0
        total = 0
        infile = open ('random_numbers.txt', 'r')
        numbers = (infile.readline())
        try:
        
            while numbers:
                numbers = numbers.strip('\n')
                numbers = int (numbers)
                print (numbers)
                total += numbers
                amount += 1
                numbers = (infile.readline())       #Move the callback here. 
        
        
        except ValueError:
            raise ValueError
        print ('')
        print ('')
        # The amount should be correct already, no need to increment by 1.
        # amount +=1
        
        print ('Your total is: ' ,total)
        print ('The amount of numbers in file is: ', amount)
        

        对我来说很好用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-14
          • 2012-03-25
          • 1970-01-01
          • 1970-01-01
          • 2014-01-26
          相关资源
          最近更新 更多