Python 从文件中读取和求和数字
这是输入文本:Python 从文件中读取和求和数字,python,Python,这是输入文本: 1 100 100 1 这是输出文本: Please enter name of input file: input.txt Please enter name of output file: output.txt Sum from 1 to 100 is 5050 Sum from 1 to 100 is 5050...etc 我的代码: def sum(): file1 = input("Plese enter name of input file:") fi
1 100
100 1
这是输出文本:
Please enter name of input file: input.txt
Please enter name of output file: output.txt
Sum from 1 to 100 is 5050
Sum from 1 to 100 is 5050...etc
我的代码:
def sum():
file1 = input("Plese enter name of input file:")
fileref = open("file1","r")
file2 = input("Plese enter name of output file:")
fileref2 = open("file2","w")
在命令提示下:
>>> print(sum())
FileNotFoundError: [Errno 2] No such file or directory: 'file1' for fileref = open("file1","r")
您传递的是字符串,而不是变量File1和File2`
您的代码中似乎有一些错误,隐藏内置和重新分配变量,并试图在不存在的行上拆分,等等。。此外,您从未实际使用过文件\u ref2
我在变量和函数名中使用了下划线,这是推荐的python方式。好吧,您需要
file1 = input("Plese enter name of input file:")
fileref = open(file1,"r")
file2 = input("Plese enter name of output file:")
fileref2 = open(file2,"w")
在开放式指令中,为什么引用变量?试试这个:fileref=openfile1,r。file2也是如此。
def sum():
file1 = input("Plese enter name of input file:")
fileref = open(file1,"r") # now the actual variable
file2 = input("Plese enter name of output file:")
fileref2 = open(file2,"w") # same here
def my_sum(): # changed to my_sum to avoid major problems when using sum in your function
file1 = input("Please enter name of input file:")
file2 = input("Please enter name of output file:")
# with close files automatically, you never use file2 but maybe you intend to write output to that
with open(file1,"r") as file_ref, open(file2,"w") as file_ref2:
result = []
# x gets reassigned in your loop below, so this is redundant
x = file_ref.readline()
for x in file_ref:
# changed to x.split(), line did not exist
n, m = x.split()
# need to be ints for range
min_number = int(min(n,m))
max_number = int(max(n,m))
for y in range(min_number, max_number):
# not sure which x you actually expected here but the current x will give an error
result.append(int(x))
# in your code you were calling your own function here
sum_result = sum(result)
print('Sum from {} to {} is {}'.format(min_number, max_number, sum_result))
# reset result for next line
result = []
# you were calling your own function again
return sum(result)
file1 = input("Plese enter name of input file:")
fileref = open(file1,"r")
file2 = input("Plese enter name of output file:")
fileref2 = open(file2,"w")