0
Hi, can any one show me how to do this test task, I'm learning how to read, write e.t.c files
The task is this You are given the following list: names= ["John", "Oscar", "Jacob"] Complete the program to create a file in which you write the names of the list, each one on a new line, and output them separately. Output: John Oscar Jacob Remember that "\ n" represents a new line. I'm not so familiarize with the functions for read and write, i know to do some things but I don't fully understand how everything works, let say i know all the the functions but I don't know how to make everything work together. If anyone can help I'll appreciate it
7 Antworten
0
this might help!
with open("test.txt","w") as file:
file.writelines(["a\n","b"])
with open("test.txt","r") as file:
print("".join(file.readlines()))
or you can read the file immediately after writing to it .
with open("test.txt","w+") as file:
file.writelines(["a\n","b"])
file.seek(0)
print("".join(file.readlines()))
______________________________
seek will make the file pointer point to the start of it .
"w+" is for reading and writing .
0
Thanks Abhay in the test code play ground give me this code:
names = ["John", "Oscar", "Jacob"]
file = open("names.txt", "w+")
#wrrite the names on the file
file.close()
file= open("names.txt", "r")
#output file content to console
file.close()
0
anthony silver with open works the same as file=open
and file.close() but in with open statement you don't have to explicitly call the close method , it does it by itself .
0
Ok
0
Abhay Can you tell me if it s necessary that I use the code that the task gave me, or can I use your code and the other code together, or only your code? Sorry I'm a little bit lost
0
anthony silver it would be better to go with what initial code sololearn gave you but there is no rule for that . You can use my as well .
And if you still don't understand anything in my code , feel free to ask !!
0
Abhay so when I make the code i put only open without an equal mark or without a dot or with a dot?