logo

Programming Languages - IO

Last Updated: 2024-01-21
  • C: fopen, fclose, fread, fwrite, fseek
  • C++: std::ofstream, std::ifstream, std::fstream

Read File

JavaScript

Read file, fs.readFile will read file as binary

var data = fs.readFileSync('data.json');
console.log(data);
//<Buffer 7b 22 32 30 30 30 22 3a 5b 7b 22 52 61 6e 6b 22 3a 31 2c 22 41 69 72 70 6f 72 74 22 3a 22 20 48 61 72 74 73 66 69 65 6c 64 2d 4a 61 63 6b 73 6f 6e 20 41 ...>

Use .toString() to get String

var str = fs.readFileSync('data.txt').toString();

Use JSON.parse() to get JSON

var data = JSON.parse(fs.readFileSync('data.json'));

Python

with open('filepath') as f:
    lines = f.read()

This will read all the lines at once, and may cause memory issue for large files.

To read and process the file line by line:

for line in open(path):
    do_something(line)

Write File

JavaScript

Write file, use JSON.stringify()

fs.writeFile('filename.json', JSON.stringify(data), null, 2);

List Files

Go

recursively visit:

filepath.Walk()

Python

Returning a list of file names:

>>> import os
>>> os.listdir(path)
['foo.txt', 'bar.txt']

JavaScript

import { statSync, readdirSync } from 'fs';

const files = [];

function getFiles(parent) {
  readdirSync(parent).forEach((filename) => {
    const filepath = parent + '/' + filename;
    if (statSync(filepath).isDirectory()) {
      getFiles(filepath);
    } else {
      files.push(filepath);
    }
  });
}

getFiles('path/to/parent/folder');

Open Files

Python

open as binary

open('filepath', 'rb')

use default codec(utf-8)

open('filepath')

Create folder if not exist

Javascrip

import { existsSync, mkdirSync } from 'fs';

const dir = 'tmp';
if (!existsSync(dir)) {
  mkdirSync(dir);
}

Python

if not os.path.exists(path):
    os.makedirs(path)

Remove if file already exists:

Python

if os.path.exists(path):
    os.remove(path)

Remove dirs recursively if dir is empty

Python

os.rmdir(path)
os.removedirs(path)

Remove dirs recursively even if they are not empty

Python

shutil.rmtree(path)

Expand Vars

Python

This will find JAVA_HOME from your settings and expand it to the path.

open(os.path.expandvars('$JAVA_HOME/foo.bar'))

Get Parent

Go

filepath.Dir()