i just want to save the output of the print statement of each for loop to a text file named test.txt and inside the text file each for loop output should be separated with >>> symbol, plus i want to put a header on the top of the text file as 'column-a'.The code i tried is below:
a = ['oof', 'rab', 'zab']
for i in range(1,5):
for file in a:
print('>>>')
data=print(file)
with open(“test.txt”,w) as f:
f.write(data)
by executing the above code i am getting out put like as below
oof
rab
zab
oof
rab
zab
oof
rab
zab
oof
rab
zab
but i need output like as below test.txt
column-a
>>>
oof
rab
zab
>>>
oof
rab
zab
>>>
oof
rab
zab
>>>
oof
rab
zab
I hope some solution i will get.Thanks in advance.
The print
statement can be used to directly write into an open file with the file
keyword argument:
items = ['oof', 'rab', 'zab']
with open('file.txt', 'w') as file:
# header
print('column-a', file=file)
# loop with >>> separators
for i in range(5):
print('>>>', file=file)
# print list items
for item in items:
print(item, file=file)
This code above creates a file.txt
file with the content:
column-a
>>>
oof
rab
zab
>>>
oof
rab
zab
>>>
oof
rab
zab
>>>
oof
rab
zab
>>>
oof
rab
zab
You just need to write to the file as well as printing to the screen. Note that you also have UTF-8 "66 & 99" double quotes in your code, not simple "
characters.
a = ['oof', 'rab', 'zab']
f = open( "test.txt", "wt" )
for i in range( 1, 5 ):
for word in a:
print( word )
f.write( word + "\n" )
print( '>>>' )
f.write( '>>>' + "\n" )
f.close()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.