我有一個非常簡單的任務,即創建一個文本文件,其中包含從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)
任何可以提供的幫助將不勝感激。
真的很感激!第一個正是我所期待的。感謝大家所有的快速反應! –