使用python从txt文件的第一个数字中减去1



我已经陷入这个问题好几个小时了。我有一个txt文件,其中的内容如下。

10 0.4600 0.4833 0.0433 0.0833
4 0.7833 0.6350 0.1167 0.0933
7 0.3583 0.4933 0.1667 0.1700

我试图在内容的第一个数字上减去1,以获得以下结果,同时保持浮点数:

9 0.4600 0.4833 0.0433 0.0833
3 0.7833 0.6350 0.1167 0.0933
6 0.3583 0.4933 0.1667 0.1700

以下是我试图解决的问题,但整个内容消失了:

path = 'file.txt'
with open(path, "r+") as f:
lines = f.readlines()
lines = str(int(lines[0].split()[0]) - 1)
with open(path, 'w') as file:
file.writelines(lines)

我真的需要帮助解决这个问题。我已经试了好几个小时了。提前感谢

lines = list()
path = 'file.txt'
with open(path, "r+") as f:
for line in f.readlines():
split_line = line.strip("n").split(" ")  # split on space character (and remove newline characters as well)
lines.append(split_line)  # add split list into list of lines


for line in lines:
line[0] = int(line[0]) - 1  # only subtract one from first element
with open(path, 'w') as file:  # rewrite to file
for line in lines:
# build the string to write
write_me = ""
for element in line:
write_me += f"{element} "
file.write(write_me + "n")

需要注意的一点是会有尾随空格和换行符。如果这是不需要的,请告诉我,我会更新这个答案。

您的解决方案无疑是一个非常准确的解决方案。我只想做一些改进:

lines = list()
path = 'file.txt'
with open(path, "r+") as f:
for line in f.read().splitlines():
# print(line)
split_line = line.split(" ")  # split on space character (and remove newline characters as well)
split_line[0] = str(
int(split_line[0]) - 1)  # update the value inside the loop. the loop used in later not needed.
lines.append(split_line)  # add split list into list of lines
# for line in lines:
#     line[0] = int(line[0]) - 1  # only subtract one from first element
with open(path, 'w') as file:  # rewrite to file
for line in lines:
# build the string to write
# write_me = ""
# for element in line:
#     write_me += f"{element} " # Another loop is not needed.
write_me = ' '.join(line)  # Use join method to add the element together
file.write(write_me + "n")

请将您的代码与我的代码进行比较,并检查改进情况。

同样,您的代码是绝对正确的,只是有一些改进的余地。如果你有其他想法,请忽略我的回答。

谢谢!

这在代码行方面会更干净:

import pandas as pd
f = 'G:\path_to_file\test.txt'
df = pd.read_csv(f, sep=" ", header=None)
df[0] = df[0]-1
print(df)

结果:

0   1       2       3       4
0   9   0.4600  0.4833  0.0433  0.0833
1   3   0.7833  0.6350  0.1167  0.0933
2   6   0.3583  0.4933  0.1667  0.1700

最新更新