我正在尝试读取.txt文件并在一行上输出打印。 .txt文件写入了随机整数。我的代码会写入这些数字,但不会将它们写在同一行。我也试图找到这些整数的总和并打印出来。我不确定我的代码有多近,但我现在卡住了。任何帮助将不胜感激。
def main():
# Open a file for reading.
infile = open('numbers.txt', 'r')
file_contents = infile.read()
infile.close()
total = (sum,file_contents)
print(file_contents,'\n',end='')
print(total)
main()
以下是编写numbers.txt文件的代码(如果有帮助的话)
import random
def main():
nums = open('numbers.txt','w') #Opens and assigns numbers.txt
#Generates integer random integer between 4 and 7
file_size = random.randint(4, 7)
#Takes the file_size integer and generates that amount
#of random integers between 5 and 19.
for num in range(file_size):
random_num = random.randrange(5,20,2)
if random_num % 2 ==1:
nums.write(str(random_num)+'\n')
nums.close()
print('Data has been written.')
main()
我已经更新了代码,但遗憾的是没有运气。
def main():
# Open a file for reading.
infile = open('numbers.txt', 'r')
file_contents = infile.read()
total += sum(int(file_contents.strip()))
infile.close()
print(file_contents)
print(total)
main()