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

弗兰克·罗德利

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

我遇到的问题是使字符串显示在同一行上。我浏览了多篇关于类似问题的文章,均无济于事。我尝试使用.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)

可以提供的任何帮助将不胜感激。

布莱克金

您的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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章