how to write to a text file using python ?

2019-09-25 06:30发布

问题:

I am trying to output a full for iteration. The output should be in a text file. How should I code for that ?

The output should look like :

Iteration 1 values --------> val1 < tab > val2 < tab > val3

Iteration 2 values --------> val4 < tab > val5 < tab > val6

This is not much of an information but I don't know where to start , can any1 show me plz ?? At the basic how should I open a text file and try and write using tabs ??

回答1:

numbers = [1,2,3,4,5,6]

with open('output.txt', 'w') as f:
  f.write('\t'.join(numbers))

Not really sure what else you mean



回答2:

file = open(filename,"w")
file.write("\t This is tabbed in \n This is a new line")
file.close()

Read here about file handling in python
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files