Home > Blockchain >  How to open a file in append mode with Python?
How to open a file in append mode with Python?

Time:01-16

I have a following python program.

f = open('file1.txt','a') 
        
temp=[] 
        
temp = input('Insert values for new  material property in the list format:\n["Name",Refectivity,Transmisivity,Slope Error(mrad),Specularity Error(mrad)]:\n') 
        
line = "\n"   temp[0]   ","   str(temp[1])   ","   str(temp[2])   ","   str(temp[3])   ","   str(temp[4]) 
        
f.write(line) 
        
f.close()

My input are:

1) "abc",13,23,34,67   
2) "cdf",12,23,34,78  
3)"dfg",23,34,56,89  

> My output should be:

["abc",13,23,34,67]     
 ["cdf",12,23,34,78]    
["dfg",23,34,56,89]  

CodePudding user response:

I think there are a number of valid suggestions and clarifications to address in the comments (i.e. using a loop, or if your input include the "1)"), but here is an implementation of what I think you need.

Assuming you want to run your program three separate times for each input to append to the file, and assuming by "in list form" you just want the output to be a string that represents the list, here is my attempt:

import ast

f = open('file1.txt','a') 
           
temp = ast.literal_eval(input('Insert values for new  material property in the list format:\n["Name",Refectivity,Transmisivity,Slope Error(mrad),Specularity Error(mrad)]:\n')) 
        
line = temp[0]   ","   str(temp[1])   ","   str(temp[2])   ","   str(temp[3])   ","   str(temp[4])

f.write("\n")
f.write("[" line "]")
        
f.close()

The input I used is:

enter image description here

Here is the output I get:

enter image description here

CodePudding user response:

something like this?

f = open("newfile.txt","w")
temp = []
print('Insert values for new  material property in the list format:\n["Name",Refectivity,Transmisivity,Slope Error(mrad),Specularity Error(mrad)]:\n')
for i in range (5):
    new = input()
    temp.append(new)

for string in temp:
    f.write(string   ",")
f.close

alternatively , as you cant write a list to a file , maybe try CSV?

  •  Tags:  
  • Related