I have a .txt file where it has a list of items that look like so:
BLAH
ONE
TWO
THREE
FOUR
I'm currently using Python to read that .txt file and print out the lines of text. The issue I'm running into is that the printed lines display the newline character of \n
and a comma together. It looks like so when I print the data from the .txt file:
BLAH \n, ONE \n, TWO \n, THREE \n, FOUR
I've tried using a .replace("\n,", "")
in an attempt to at least get rid of the unwanted characters, but that does not seem to be working. How can I get maintain the same format from the .txt file through Python commands?
By request, here is my code:
file = open("plstemp.txt", "r")
abc=str(file.readlines())
wow = abc.replace("[", "").replace("]", "").replace("'", "")
print(wow)
file.close()
My desired output is as follows:
BLAH
ONE
TWO
THREE
FOUR
As suspected, you are using
readlines
which will give you a list. Where each item in the list is a line from your file. You do not need to do that whole replacement of '['. You need to realize here you actually have a list.So, doing
file.readlines()
, you will have:If you use
file.read()
instead and print out the result of that:Keep in mind, you still have a '\n', because you actually need it to have the output above, since '\n' actually is a special character meaning "newline".
So, to re-write your code, you can simply do (you don't need to specify "r" since it is "r" by default):
readlines
return the lines of your file as a list, but then you apply thestr
function to the list, which converts the list into a string; this is why you get the unwanted[
and]
.If you simply want to read in the whole file, you could do the following
Also avoid using
file
as a variable name, because it is a built-in type of python.Ok it's clearer now that I see your code :)
readlines()
, aswell as afor
loop will return a list. You are using astr()
fonction on a list which I think won't work. I assume idjaw's answer is right. You could try aswell :