this is my first post here to stackoverflow, and I am still just learning Python and programming in general. I'm working on some simple game logic, and I'm getting a little washed up on how Python handles file input/output.
What I'm trying to do is, while my game is running, store a series of variables (all numeric, integer data), and when the game is over, dump that information to txt file that can later be read (again, as numeric, integer data) so that it can be added to. A tracker, really.
Perhaps if you were playing some racing game, for example, every time you hit a pedestrian, pedestrians += 1. Then when your game is over, after hitting like 23 pedestrians, that number (along with any other variables I wished to track) is saved to a text file. When you start the game again, it loads the number 23 back into the pedestrians variable, so if you hit 30 more this time you end up with 53 total, and so on. Thanks in advance!
Does it have to be text? I'd use pickle if not
http://docs.python.org/library/pickle.html
There are quite a few ways to do this. Do you want the file to be human-readable or human-writable? (Could encourage cheating if you do.)
The simplest thing that you could do which would work is to use the ConfigParser library, which stores simple data like what you described in a text file. Something like:
Reading:
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open('game_data.dat'))
dead_pedestrians = config.getint('JoeUser', 'dead_pedestrians')
Writing:
config = ConfigParser.RawConfigParser()
config.add_section('JoeUser')
config.set('JoeUser', 'dead_pedestrians', '15')
with open('game_data.dat', 'wb') as configfile:
config.write(configfile)
Other options: If you don't want it to be human-readable, you could use shelve (but a clever user who knows you're using python would find it trivial to read.
Hope that helps!
Related
I'm trying to analyze a midi file with music21 to get the keys of that file. Does anyone know the command for that or where to find an example for this?
I'm new to this.
Thank you a lot in advance.
Assuming you need to analyze with a key-finding algorithm (as opposed to just reading the key signature provided by the encoder, if present), then create a music21.stream.Score and call analyze("key"):
my_score: music21.stream.Score = music21.converter.parse('path.mid')
k = my_score.analyze('key')
print(k.name)
Some other fun stuff like alternateInterpretations and correlationCoefficient are described in the User's Guide. Enjoy!
I'am trying to get lines from a text file (.log) into a .txt document.
I need get into my .txt file the same data. But the line itself is sometimes different. From what I have seen on internet, it's usualy done with a pattern that will anticipate how the line is made.
1525:22Player 11 spawned with userinfo: \team\b\forcepowers\0-5-030310001013001131\ip\46.98.134.211:24806\rate\25000\snaps\40\cg_predictItems\1\char_color_blue\34\char_color_green\34\char_color_red\34\color1\65507\color2\14942463\color3\2949375\color4\2949375\handicap\100\jp\0\model\desann/default\name\Faybell\pbindicator\1\saber1\saber_malgus_broken\saber2\none\sex\male\ja_guid\420D990471FC7EB6B3EEA94045F739B7\teamoverlay\1
The line i'm working with usualy looks like this. The data i'am trying to collect are :
\ip\0.0.0.0
\name\NickName_of_the_player
\ja_guid\420D990471FC7EB6B3EEA94045F739B7
And print these data, inside a .txt file. Here is my current code.
As explained above, i'am unsure about what keyword to use for my research on google. And how this could be called (Because the string isn't the same?)
I have been looking around alot, and most of the test I have done, have allowed me to do some things, but i'am not yet able to do as explained above. So i'am in hope for guidance here :) (Sorry if i'am noobish, I understand alot how it works, I just didn't learned language in school, I mostly do small scripts, and usualy they work fine, this time it's way harder)
def readLog(filename):
with open(filename,'r') as eventLog:
data = eventLog.read()
dataList = data.splitlines()
return dataList
eventLog = readLog('games.log')
You'll need to read the files in "raw" mode rather than as strings. When reading the file from disk, use open(filename,'rb'). To use your example, I ran
text_input = r"1525:22Player 11 spawned with userinfo: \team\b\forcepowers\0-5-030310001013001131\ip\46.98.134.211:24806\rate\25000\snaps\40\cg_predictItems\1\char_color_blue\34\char_color_green\34\char_color_red\34\color1\65507\color2\14942463\color3\2949375\color4\2949375\handicap\100\jp\0\model\desann/default\name\Faybell\pbindicator\1\saber1\saber_malgus_broken\saber2\none\sex\male\ja_guid\420D990471FC7EB6B3EEA94045F739B7\teamoverlay\1"
text_as_array = text_input.split('\\')
You'll need to know which columns contain the strings you care about. For example,
with open('output.dat','w') as fil:
fil.write(text_as_array[6])
You can figure these array positions from the sample string
>>> text_as_array[6]
'46.98.134.211:24806'
>>> text_as_array[34]
'Faybell'
>>> text_as_array[44]
'420D990471FC7EB6B3EEA94045F739B7'
If the column positions are not consistent but the key-value pairs are always adjacent, we can leverage that
>>> text_as_array.index("ip")
5
>>> text_as_array[text_as_array.index("ip")+1]
'46.98.134.211:24806'
I'm new here and to python in general, so please forgive any formatting issues and whatever else. I'm a physicist and I have a parametric model, where I want to iterate over one or more of the model's parameter values (possibly in an MCMC setting). But for simplicity, imagine I have just a single parameter with N possible values. In a loop, I compute the model and several scalar metrics pertaining to it.
I want to save the data [parameter value, metric1, metric2, ...] line-by-line to a file. I don't care what type: .pickle, .npz, .txt, .csv or anything else are fine.
I do NOT want to save the array after all N models have been computed. The issue here is that, sometimes a parameter value is so nonphysical that the program I call to calculate the model (which is a giant complicated thing years in development, so I'm not touching it) crashes the kernel. If I have N = 30000 models to do, and this happens at 29000, I'll be very unhappy and have wasted a lot of time. I also probably have to be conscious of memory usage - I've figured out how to do what I propose with a text file, but it crashes around 2600 lines because I don't think it likes opening a text file that long.
So, some pseudo-code:
filename = 'outFile.extension'
dataArray = np.zeros([N,3])
idx = 0
for p in Parameter1:
modelOutputVector = calculateModel(p)
metric1, metric2 = getMetrics(modelOutputVector)
dataArray[idx,0] = p
dataArray[idx,1] = metric1
dataArray[idx,2] = metric2
### Line that saves data here
idx+=1
I'm partial to npz or pickle formats, but can't figure out how to do this with either. If there is a better format or a better solution, I appreciate any advice.
Edit: What I tried to make a text file was this, inside the loop:
fileObject = open(filename, 'ab')
np.savetxt(fileObject, rowOfData, delimiter = ',', newline = ' ')
fileObject.write('\n')
fileObject.close()
The first time it crashed at 2600 or whatever I thought it was just coincidence, but every time I try this, that's where it stops. I could hack it and make a batch of files that are all 2600 lines, but there's got to be a better solution.
Its hard to say with such a limited knowledge of the error, but if you think it is a file writing error maybe you could try something like:
with open(filename, 'ab') as fileObject:
# code that computes numpy array
np.savetxt(fileObject, rowOfData, delimiter = ',', newline = ' ')
fileObject.write('\n')
# no need to .close() because the "with open()" will handle it
However
I have not used np.savetxt()
I am not an expert on your project
I do not even know if it is truly a file writing error to begin with
I just prefer the with open() technique because that's how all the introductory python books I've read structure their file reading/writing processes, so I assume there is wisdom in it. You could also consider doing like fabianegli commented and save to separate files (thats what my work does).
I'm currently working on a simple Python 3.4.3 and Tkinter game.
I struggle with saving/reading data now, because I'm a beginner at coding.
What I do now is use .txt files to store my data, but I find this extremely counter-intuitive, as saving/reading more than one line of data requires of me to have additional code to catch any newlines.
Skipping a line would be terrible too.
I've googled it, but I either find .txt save/file options or way too complex ones for saving large-scale data.
I only need to save some strings right now and be able to access them (if possible) by key like in a dictionary key:value .
Do you know of any file format/method to help me accomplish that?
Also: If possible, should work on Win/iOS/Linux.
It sounds like using json would be best for this, which comes as part of the Python Standard library in Python-2.6+
import json
data = {'username':'John', 'health':98, 'weapon':'warhammer'}
# serialize the data to user-data.txt
with open('user-data.txt', 'w') as fobj:
json.dump(data, fobj)
# read the data back in
with open('user-data.txt', 'r') as fobj:
data = json.load(fobj)
print(data)
# outputs:
# {u'username': u'John', u'weapon': u'warhammer', u'health': 98}
A popular alternative is yaml, which is actually a superset of json and produces slightly more human readable results.
You might want to try Redis.
http://redis.io/
I'm not totally sure it'll meet all your needs, but it would probably be better than a flat file.
I'm trying to make a siren sound in python with beeps, but had no success..
I'm trying something like
winsound.Beep(700,500)
winsound.Beep(710,500)
winsound.Beep(720,500)
...
It's a better way to do it? And play it?
Without external files...
Thx
Record a high quality siren as a WAV file (Audacity is a nice tool for this task, and might even provide the right mix of sound generators for this) and use PlaySound.
winsound.PlaySound('siren.wav', winsound.SND_FILENAME)
You could also bundle it into the script as a string to avoid having a separate file:
siren = base64.b64decode('''
<base64-encoded data>
''')
winsound.PlaySound(siren, winsound.SND_MEMORY)
To create the data for siren, run the WAV file through a base64 encoder (e.g., here is a basic command-line tool — the download includes a win32 exe) and paste the output into the siren string. Base64 isn't a requirement, by the way; it's just a convenient way to embed binary data into a Python source file.
I remember using something similar on QBASIC when I was still a kid:
DO
FOR n = -180 TO 180 STEP .1
f = 440 + 50 * SIN(n)
SOUND f, 1
NEXT
LOOP
SOUND f, 1 should be the same thing as winsound.Beep, with pitch and duration. It used to work great but since I took the snippet here I'm not sure I did exactly this way.
It's just to give you the idea..