0
Reading and writing in files
So theres this exercise (Lesson 49.2) where i have to open a file, write in it, close it, open it again, read it and print it. How do i do it?
15 odpowiedzi
+ 2
There are some examples in the lessons. What errors/ problems did you encounter? Can you show us your code?
+ 2
Okay, in the beginning names is a list of strings.
You could use join() to make them one single string. If you use "\n" to join, you get the line breaks.
If you have the string like this, you can write it to the file.
+ 2
Join is a built-in string method:
https://www.w3schools.com/JUMP_LINK__&&__python__&&__JUMP_LINK/ref_string_join.asp
Of course you can also loop through the list and concatenate the strings like "line 1" + "\n" + "line 2"
+ 1
"\n".join(your_list)
+ 1
names = ["John", "Oscar", "Jacob"]
file = open("names.txt", "w+")
file.write(("\n".join(names))
file.close()
file= open("names.txt", "r")
r = file.read()
print(r)
file.close()
file.close() is an invalid syntax, why?
+ 1
In your 3rd line (file.write) is one opening bracket too many. Remove it.
+ 1
tho i have never learned about join() except from the battles against people for exp
is there another way for me to make the same exercise but with the limited stuff i know
0
names = ["John", "Oscar", "Jacob"]
file = open("names.txt", "w+")
i = file.write(str(names))
file.close()
file= open("names.txt", "r")
r = file.read()
print(r)
file.close()
0
Your code shows no error.
It seems to be a pro project, I cannot see what the task is.
Please explain, what you are trying to do.
0
so i was given the list
names = ["John", "Oscar", "Jacob"]
and i was supposed to
complete the program to create a file where you write the names from the list, each on a nrw line, and seperatly output them
so the output should be
John
Oscar
Jacob
0
wait do i do .join(\n)?
0
alright thanks for the help!
0
alright it works
0
names = ["John", "Oscar", "Jacob"]
file = open("names.txt", "w+")
for i in names:
file.write(i+"\n")
file.close()
file= open("names.txt", "r")
print(file.read())
file.close()
0
Hello people, the topic is closed, but I was just going through this task, and solved it with the help of this code. And only then decided to take a look, after all, it was more correct. Many thanks to the last author of the comment.
names = ["John", "Oscar", "Jacob"]
file = open("names.txt", "w+")
conte = "{} {} {}".format(*names)
conte = conte.replace(" ", "\n")
file.writelines(conte)
file.close()
file= open("names.txt", "r")
print(file.read())
file.close()