I have a script that reads a file. The file contains lines of text data, each line corresponds to a player and each attribute of a player is separated by a tab.
My script breaks apart the line into an array for each player, then simply reconstructs the data into a string that I want to save to a separate file, so that each individual line in the new file corresponds to a player:
# -*- coding: utf-8 -*-
def main():
exampleDataFile = open("exampleData.txt", "r")
dataStorageFile = open("playerStrings.txt", "w+")
for line in exampleDataFile:
modifiedLine = line.replace('“','"').replace('”','"')
listOfComponents = modifiedLine.split("\t")
uid = listOfComponents[0]
gamerID = listOfComponents[1]
userPhoneNumber = listOfComponents[2]
_geoloc = listOfComponents[3]
allocatedTimes = listOfComponents[4]
clanName = listOfComponents[5]
gamerString = ('let ' + uid + ' = player(gamerID: "' + gamerID + '", userPhoneNumber: "' + userPhoneNumber + '", _geoloc: makeCoordinates(points: (' + _geoloc + ")), allocatedTimes: makeallocatedTimes(" + allocatedTimes + '), clanName: "' + clanName + '")\n')
print (gamerString)
dataStorageFile.write(gamerString)
if __name__ == '__main__':
main()
When I check the logs and also the file that the output was saved to, the first output is printed/saved to a single line, which is exactly what i want. However, all subsequent lines are broken off at the final '")\n'
. What I get is this:
let r2 = player(gamerID: "TE2", userPhoneNumber: "3456106340", _geoloc: makeCoordinates(points: (51.563601, -0.118769)), allocatedTimes: makeallocatedTimes(mon:("0700","2300"),tue:("0700","2300"),wed:("0700","2300"),thu:("0700","2300"),fri:("0700","2300"),sat:("0700","2300"),sun:("0700","2300")), clanName: "Tesco
")
Notice how the ")
is on a separate line. This is not what I want, I want it like this:
let r2 = player(gamerID: "TE2", userPhoneNumber: "3456106340", _geoloc: makeCoordinates(points: (51.563601, -0.118769)), allocatedTimes: makeallocatedTimes(mon:("0700","2300"),tue:("0700","2300"),wed:("0700","2300"),thu:("0700","2300"),fri:("0700","2300"),sat:("0700","2300"),sun:("0700","2300")), clanName: "Tesco")
I have tried printing out very long strings and they all print/save to a single line for each print, but for some reason when I print/save the gamer output, I get the ")
on a separate line and I'm not sure why? Thanks!
Python does not strips newline characters at the end of the line when reading file. That means that file with content like
row1,value1
row2,value2
Will be read as two strings, containing "row1,value1\n"
and " row2,value2\n"
.
Make something like modifiedLine = line.strip('\n')
as part of cleaning/preprocessing.