Reputation:
I'm a beginner with Python and would appreciate some help. I'm having trouble with the code below as I can't split a file. In my text file I have Gem11 and Gem12 on separate lines and would like to know how to display it in Python in the same format without the quotation marks.
with open ("testpractice01.txt" , "r") as f:
f_contents = f.readlines()
print (f_contents)
f.close()
Here's what python is generating. I'm trying to remove the quotation marks etc so I simply have Gem11 and Gem12 so I can then place these in a variable to search through later:
['Gem11\n', 'Gem12\n']
Upvotes: 2
Views: 123
Reputation: 11
Instead of using readlines, use readline.
with open ("test.txt" , "r") as f:
for line in f:
print (line)
f.close()
Upvotes: 0
Reputation: 402323
Quotation marks are how python demarcates strings. The actual object string does not contain the quotations marks. Try printing each string with print
and you'll see those quotes disappear.
The other thing to note is the trailing newline in your lines, because file lines are read in with the trailing newline by default, so you'll need to call str.strip()
to get rid of it. I'd recommend iterating over f
, the file object, so doing this becomes easier.
f_contents = []
with open ("testpractice01.txt" , "r") as f:
for line in f:
f_contents.append(line.strip())
for line in f_contents:
print(line)
Upvotes: 2