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