Fix Python – Python: How to create a unique file name?

I have a python web form with two options – File upload and textarea. I need to take the values from each and pass them to another command-line program. I can easily pass the file name with file upload options, but I am not sure how to pass the value of the textarea.
I think what I need to do is:

Generate a unique file name
Create a temporary fil….

Fix Python – How can I detect if a file is binary (non-text) in Python?

How can I tell if a file is binary (non-text) in Python?
I am searching through a large set of files in Python, and keep getting matches in binary files. This makes the output look incredibly messy.
I know I could use grep -I, but I am doing more with the data than what grep allows for.
In the past, I would have just searched for characters greate….

Fix Python – Writing to a new file if it doesn’t exist, and appending to a file if it does

I have a program which writes a user’s highscore to a text file. The file is named by the user when they choose a playername.
If the file with that specific username already exists, then the program should append to the file (so that you can see more than one highscore). And if a file with that username doesn’t exist (for example, if the user is ….

Fix Python – How to write to a CSV line by line?

I have data which is being accessed via http request and is sent back by the server in a comma separated format, I have the following code :
site= ‘www.example.com’
hdr = {‘User-Agent’: ‘Mozilla/5.0’}
req = urllib2.Request(site,headers=hdr)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
soup = soup.get_text()
text=str(soup)

The content of….

Fix Python – Copy file with pathlib in Python

I try to copy a file with pathlib
import pathlib
import shutil

my_file=pathlib.Path(‘/etc/hosts’)
to_file=pathlib.Path(‘/tmp/foo’)
shutil.copy(my_file, to_file)

I get this exception:
/home/foo_egs_d/bin/python /home/foo_egs_d/src/test-pathlib-copy.py
Traceback (most recent call last):
File “/home/foo_egs_d/src/test-pathlib-copy.py”, line 6, in….

Fix Python – Read and overwrite a file in Python

Currently I’m using this:
f = open(filename, ‘r+’)
text = f.read()
text = re.sub(‘foobar’, ‘bar’, text)
f.seek(0)
f.write(text)
f.close()

But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it.
….

Fix Python – Loading and parsing a JSON file with multiple JSON objects

I am trying to load and parse a JSON file in Python. But I’m stuck trying to load the file:
import json
json_data = open(‘file’)
data = json.load(json_data)

Yields:
ValueError: Extra data: line 2 column 1 – line 225116 column 1 (char 232 – 160128774)

I looked at 18.2. json — JSON encoder and decoder in the Python documentation, but it’s pretty d….