Python函数在文本文件中的多个单独的行



我试图写一个函数,可以采取每一个单独的行在一个txt文件,并将该行乘以2,使文本文件中的每个整数加倍。目前为止,我能把代码打印出来。然而,当我添加代码(阅读&Reading_int)将字符串转换为整数的函数现在不起作用。代码中没有错误来告诉我我做错了什么。我不确定什么是错误的阅读和reading_int,使我的函数不工作。

def mult_num3():
data=[]
w = open('file3.txt', 'r')
with w as f:
reading = f.read()
reading_int = [int(x) for x in reading.split()]
for line in f:
currentline = line[:-1]
data.append(currentline)
for i in data:
w.write(int(i)*2)
w.close()

file3.txt:

1
2
3
4
5
6
7
8
9
10

所需输出:

2
4
6
8
10
12
14
16
18
20

原始代码问题:

def mult_num3():
data=[]
w = open('file3.txt', 'r')  # only opened for reading, not writing
with w as f:
reading = f.read()  # reads whole file
reading_int = [int(x) for x in reading.split()] # unused variable
for line in f:  # file is empty now
currentline = line[:-1] # not executed
data.append(currentline) # not executed
for i in data:  # data is empty, so...
w.write(int(i)*2) # not executed, can't write an int if it did
# and file isn't writable.
w.close() # not necessary, 'with' will close it

请注意,int()忽略了前后空白,因此如果每行只有一个数字,则不需要.split(),并且格式字符串(f-string)可以根据需要通过转换和加倍值并添加换行来格式化每行。

with open('file3.txt', 'r') as f:
data = [f'{int(line)*2}n' for line in f]
with open('file3.txt', 'w') as f:
f.writelines(data)

我添加了一个尝试,除了检查非整数数据。我不知道你的数据。但也许它对你有帮助。

def mult_num3():
input = open('file3.txt', 'r')
output = open('script_out.txt', 'w')
with input as f:
for line in f:
for value in line.split():
try:
output.write(str(int(value) * 2) + " ")
except:
output.write(
"(" + str(value + ": is not an integer") + ") ")
output.write("n")
output.close()

最新更新