Reputation: 3431
Hello I'm making a python program that takes in a file. I want this to be set to a single string. My current code is:
with open('myfile.txt') as f:
title = f.readline().strip();
content = f.readlines();
The text file (simplified) is:
Title of Document
asdfad
adfadadf
adfadaf
adfadfad
I want to strip the title (which my program does) and then make the rest one string. Right now the output is:
['asdfad\n', 'adfadadf\n', ect...]
and I want:
asdfadadfadadf ect...
I am new to python and I have spent some time trying to figure this out but I can't find a solution that works. Any help would be appreciated!
Upvotes: 3
Views: 8016
Reputation: 142136
Another option is to read the entire file, then remove the newlines instead of joining together:
with open('somefile') as fin:
next(fin, None) # ignore first line
one_big_string = fin.read().replace('\n', '')
Upvotes: 0
Reputation: 8147
Use list.pop(0)
to remove the first line from content.
Then str.join(iterable). You'll also need to strip off the newlines.
content.pop(0)
done = "".join([l.strip() for l in content])
print done
Upvotes: 0
Reputation: 103764
You can do this:
with open('/tmp/test.txt') as f:
title=f.next() # strip title line
data=''.join(line.rstrip() for line in f)
Upvotes: 6
Reputation: 3130
If you want the rest of the file in a single chunk, just call the read()
function:
with open('myfile.txt') as f:
title = f.readline().strip()
content = f.read()
This will read the file until EOF is encountered.
Upvotes: -1