I have a file values.txt with hierarchical formatting like this:
group1
subgroup1
value1
value2
group2
subgroup2
value3
value4
if in 开发者_StackOverflow社区bash i execute
echo $(cat values.txt)
I will get the output:
group1 subgroup1 value1 value2 group2 subgroup2 value3 value4
I would like to get this string formatted the same exact way from inside the python script, so it will be very easy to split it by whitespace for further processing.
Thanks!
As Byron points out, split
splits on whitespace by default, so you should be able to do just
contents = open("values.txt", "r").read().split()
and have the list you want, combining the two steps you described. If you have some other use for the intermediate "string formatted the exact same way", you can produce it from the split list with
" ".join(contents)
with open('values.txt') as file:
data = file.read()
data = ' '.join(data.split())
print data
# or just:
data = file.read().split()
精彩评论