簡體   English   中英

使用 python 從 txt 文件的第一個數字中減去 1

[英]Subtracting 1 from the first number of a txt file using python

我已經被這個問題困了幾個小時了。 我有一個 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")

請將您的代碼與我的代碼進行比較並檢查改進。

同樣,您的代碼是絕對正確的,只是對 scope 進行了一些改進。 如果您有其他感覺,請忽略我的回答。

謝謝!

就代碼行而言,這會更干凈:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM