I am trying to get an output that looks like this:
'a',
'abandon',
'ability',
'able',
These lines should look like a list, I'm new and didn't know what to do XD
what I am getting
'a
','abandon
','ability
','able
here is my code:
`f = open("he.txt", "r")
for i in range(0,3000):
print(f.readline(),"',", sep="", end='')
close()`
also, is there any way I can write this to a file? I have been looking for a way and couldn't find one, it interferes with reading the file.
What is the content of f(Can you paste it?)? Also, it's best practice using context manager when reading from files, right now you are not checking for failure when opening the file. Use with
statement, eg - with open("he.txt", "r") as in_file: ...
and the file will be closed when you leave the context without manually taking care of it.
A newline is included at the end of every line in a file. To get around this, you can use rstrip
to strip a character at the end of a string. For example:
f = open("he.txt", "r")
for i in range(0,3000):
line = f.readline()
line = line.rstrip("\n") # strip trailing newline
print(line, "',")
close()
You can change your code like this:
f = open("he.txt", "r") for i in range(0,3000): print(f.readline().rstrip(),"',", sep="", end='') close()
.rstrip() removes the whitespace at the end of the word
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.