#Community Practice Problem ( File Handling)

Write a python program to write a list to a file.

1 Like

file = open(“new_file.txt”, ‘w’)
file.write(“list”)
file.close()

2 Likes

li = [“1\n”, “2\n”, “3\n”,“4\n”,“5\n”]
with open(“C:\Users\VKU Lakra\Desktop\Python\new_file.txt”, ‘w’) as filehandler:
print(filehandler.writelines(li))

2 Likes

li=[]
with open(“mylist.txt”,‘w’) as filehandler:
li=filehandler.write(“10”)
li=filehandler.write(“20”)

2 Likes

Answer:

my_list = [1, 2, 3, 4, 5]

Open file in write mode and create it if it doesn’t exist

with open(‘my_file.txt’, ‘w’) as file:
for item in my_list:
file.write(str(item) + ‘\n’)

2 Likes

file = open(“file.txt”, ‘w’)
file.write(“list”)
file.close()

2 Likes

file = open(“test.txt”, ‘w’)
file.write(“list”)
file.close()

2 Likes

open(‘file.txt’, ‘w’):
for item in my_list:
file.write(str(item) + ‘\n’)
file.close()

2 Likes

f= open(“op.txt”,‘w’)
f.write(“Ram”)

2 Likes

f=open(“file.name”,“w”)
f.write()

2 Likes

l1 = [“Edyoda”, “program”]
with open(“test.txt”, ‘w’) as file:
for item in 11:
file.write(item)

2 Likes

file=open(“myfile.txt”,‘w’)
file.write(“list”+‘/n’)
file.close()

2 Likes

with open(“my_file.txt”, “w”) as f:
for item in my_list:
f.write(item + “\n”)

2 Likes

Very well done everyone, I am happy that you all made efforts and tried out the problem. Keep it up guys.

2 Likes

list_ = [‘apple’,‘ball’,‘cat’,‘dog’]
with open(‘list.txt’,‘w’) as file:
for i in list_:
print(i)
file.write(i)
file.write(" ")

1 Like

mam for this code its showing error like- I/O operation on closed file.

1 Like

@nagmafariyal2017

Run the program in your IDE and show me the error?

1 Like

yes mam resolved the issue…there was indentation problem
list_ = [‘apple’,‘ball’,‘cat’,‘dog’]
with open(‘list.txt’,‘w’) as file:
for i in list_:
print(i)
file.write(i)
file.write(" ")