在一行上显示文件中的整数

时间:2016-02-16 04:00:38

标签: python python-3.x

我有一个非常简单的任务,即创建一个包含1-100个随机整数的文本文件,读取文件,在同一行显示数字,计算偶数整数和奇数整数,然后显示它们。

我遇到的问题是让字符串显示在同一行。我浏览了多篇关于类似问题的文章但无济于事。我试图使用.join,但是,当我包含它时它似乎打破了代码。

# Imports random and time 
import random
import time

# Defines the main function 
def main():

    # Opens file "mynumbers" and creates it if not existent 
    myfile = open('mynumbers.txt', 'w')

    # Statement to write intergers to text file in the correct format
    for count in range(8):
        number = random.randint(1, 100)
        myfile.write(str(number) + '\n')

# Defines read function 
def read():

    # Opens the "mynumbers" file created in the main function 
    myfile= open('mynumbers.txt', 'r')

    # Sets the content variable to the content of the file that was opened 
    content = myfile.read()

    # Prints the content variable and strips the \n from the string
    stripit = content.rstrip('\n')
    print(stripit)


# Calls for the functions, prints created, and sleep calls
main()
print('File Created!')
time.sleep(1)
read()
time.sleep(5)

我们将非常感谢您提供的任何帮助。

5 个答案:

答案 0 :(得分:1)

编写文件时不要添加换行符。只需使用空格(或逗号,无论如何)

import random
import time

#Defines the main function
def main():

#Opens file "mynumbers" and creates it if not existent
    myfile = open('mynumbers.txt', 'w')

#Statement to write intergers to text file in the correct format
    for count in range(8):
        number = random.randint(1,100)
        myfile.write(str(number) +' ')

#Defines read function
def read():

#Opens the "mynumbers" file created in the main function
    myfile= open('mynumbers.txt', 'r')

#Sets the content variable to the content of the file that was opened
    content=myfile.read()

#Prints the content variable and strips the \n from the string
    print(content)



#Calls for the functions, prints created, and sleep calls
main()
print('File Created!')
time.sleep(1)
read()
time.sleep(5)

答案 1 :(得分:1)

您的read函数正在将整个文件内容读入单个字符串。您对该字符串的rstrip调用将删除其中的最后一个换行符,但不会删除任何内部换行符。您无法有效使用str.join,因为您只有一个字符串。

我认为有两种合理的解决方案。第一种是仅保留一个字符串,但用空格替换所有内部换行:

def read():
    myfile = open('mynumbers.txt', 'r')
    content = myfile.read()
    stripit = content.rstrip('\n')
    nonewlines = stripit.replace('\n', ' ')
    print(nonewlines)

另一种方法是将单个字符串拆分为单独字符串列表,每个字符串对应一个字符串。如果我们稍后需要对它们做不同的事情,这会更有用。当然,我们要做的就是使用join将它们组合在一起:

def read():
    myfile = open('mynumbers.txt', 'r')
    content = myfile.read()
    content_list = content.split() # by default, splits on any kind of whitespace
    rejoined_content = " ".join(content_list)
    print(rejoined_content)

答案 2 :(得分:0)

代码看起来很棒但是在read()函数上执行此操作。

def read():
     my_numbers = []
     with open('mynumbers.txt', 'r') as infile:
          for line in infile:
               line = line.strip()
               my_numbers.append(line)
     print (' '.join(line))

答案 3 :(得分:0)

我会这样做,特别是因为你提到了你接下来需要做的偶数和奇数部分。在第一个循环结束时,您将拥有一个可以使用的int(而不是strs)列表,并确定它们是偶数还是奇数。

def read():
     my_nums = []
     with open('mynumbers.txt', 'r') as f:
          for line in f:
               num_on_line = int(line.strip())
               my_nums += [num_on_line]
               print num_on_line, #don't forget that comma
     for num in my_nums:
          #display the even and odds

答案 4 :(得分:0)

您可以用这种方式在一行中打印数字

$ gulp sass
[18:52:30] Using gulpfile ~/path_to_project/gulpfile.js
[18:52:30] Starting 'sass'...
[18:52:30] Finished 'sass' after 37 ms

with open('mynumbers.txt', 'r') as numbers_file: for line in numbers_file: print(line.strip(), end=" ") 用于消除line.strip()字符。