I have a space-separated text file. Each line has a one item followed by zero or more additional items. All values are strings.
I wish to output the data as key-value pairs.
How can this be done in Python?
Input:
1: 200
2:
3: 300 400 abc
4: xyz 300
Desired Output:
1: 200
2:
3: 300
3: 400
3: abc
4: xyz
4: 300
If it makes it easier, line 2 could be omitted from the output. Output will be sorted by key (1st column).
Code starter:
# Open the text file
file = open("data.txt", "r")
# Read each \n terminated line into a list called 'lines'
lines = file.readlines()
# Iterate through each line
for line in lines:
# Remove leading/trailing spaces and newline character
line = line.strip()
# Split the line into list items (but the number varies with each line)
.... = line.split(" ")
.
.
?
Using a simple iteration.
Ex:
result = []
with open(filename) as infile:
for line in infile: #Iterate each line
key, val = line.split(":") #Get key-value
for i in val.strip().split():
result.append((key, i))
with open(filename, "w") as outfile: #Write Output
for line in result:
outfile.write(": ".join(line) + "\n")
Output:
1: 200
3: 300
3: 400
3: abc
4: xyz
4: 300
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.