unknown----- unknown----- - 1 year ago 245
Python Question

Splitting text file in python

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)

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']

Answer Source

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:

for line in f_contents:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download