如何以交互方式在文件中添加新信息?蟒蛇

问题描述 投票:0回答:0

您好,我一直在尝试向我的文件添加新信息。但添加方式错误 我想要这样添加信息

Ag 22.16 24.94
Ni 7.48 8.26
Cr 5.41 5.95
Pb 74.96 84.92
Al 1.49 1.55
Cu 8.05 8.90
Rh 20.21 22.72
Hg 70.82 80.26

但是使用我的代码重写了最后一行并且不添加新信息。我的意思是这个。它只是更改文档的最后一行并重写它。例如,如果我添加 Zn 8.54 9.57。现在文件不再包含新元素和其他元素。具有所有其他元素,但不是汞,而是锌

我试过这个

# Nombre del directorio específico
directory_path = '/content/drive/MyDrive/ProjetoXRF_Manuel/'

# Nombre del archivo de texto
file_name = "informacion.txt"

# Pedir al usuario la nueva información
new_info = input("Enter the new information (Format: Symbol Value1 Value2): ")

# Agregar nueva información al archivo
with open(directory_path + file_name, 'a') as file:
    file.write("\n" + new_info)  # Agregar nueva información en una nueva línea
print("Data has been added to", directory_path + file_name)
python file edit txt
© www.soinside.com 2019 - 2024. All rights reserved.