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

标签 python python-3.x

我有一个非常简单的任务,即创建一个包含 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)

关于python - 在一行上显示文件中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35423473/

相关文章:

python - 如何将 Pyspark DataFrame 写入 XML 格式?

python - 创建类似 MS Office 文档的文件格式以公开文档属性

jquery - Flask View 的 JSON "POST"不起作用

python - Pandas - `loc` 在除一列之外的所有列上返回空 DataFrame

python - 检查json对象中的路径是否存在?

python - 尝试在 python 中一次搜索 2 个字符

python - 在 linux 上登录时运行我的 Python 脚本

python-2.7 - 如何在 Python 2 中模仿 Python 3 的加薪...?

python-3.x - 将 Jupyter kernelspec 更改为指向 anaconda python

python - 在Python中将列表转换为字典