Basic http file downloading and saving to disk in python?

A clean way to download a file is: import urllib testfile = urllib.URLopener() testfile.retrieve(“http://randomsite.com/file.gz”, “file.gz”) This downloads a file from a website and names it file.gz. This is one of my favorite solutions, from Downloading a picture via urllib and python. This example uses the urllib library, and it will directly retrieve the file form … Read more

How to create a file in Ruby

Use: File.open(“out.txt”, [your-option-string]) {|f| f.write(“write your stuff here”) } where your options are: r – Read only. The file must exist. w – Create an empty file for writing. a – Append to a file.The file is created if it does not exist. r+ – Open a file for update both reading and writing. The … Read more

Get last n lines of a file, similar to tail

This may be quicker than yours. Makes no assumptions about line length. Backs through the file one block at a time till it’s found the right number of ‘\n’ characters. def tail( f, lines=20 ): total_lines_wanted = lines BLOCK_SIZE = 1024 f.seek(0, 2) block_end_byte = f.tell() lines_to_go = total_lines_wanted block_number = -1 blocks = [] … Read more

How to delete a specific line in a file?

First, open the file and get all your lines from the file. Then reopen the file in write mode and write your lines back, except for the line you want to delete: with open(“yourfile.txt”, “r”) as f: lines = f.readlines() with open(“yourfile.txt”, “w”) as f: for line in lines: if line.strip(“\n”) != “nickname_to_delete”: f.write(line) You … Read more

__FILE__ macro shows full path

Try #include <string.h> #define __FILENAME__ (strrchr(__FILE__, “https://stackoverflow.com/”) ? strrchr(__FILE__, “https://stackoverflow.com/”) + 1 : __FILE__) For Windows use ‘\\’ instead of “https://stackoverflow.com/”.

How to read a (static) file from inside a Python package?

TLDR; Use standard-library’s importlib.resources module as explained in the method no 2, below. The traditional pkg_resources from setuptools is not recommended anymore because the new method: it is significantly more performant; is is safer since the use of packages (instead of path-stings) raises compile-time errors; it is more intuitive because you don’t have to “join” … Read more