Short code examples on reading and writing to text files.

Open file, print contents line by line

If you can print a file line by line, of course, you can do whatever you like with that line.

with open('filename.txt', 'r') as f:
    for line in f:
        print(line.rstrip())
def handle_line(line):
    print(line)

map(handle_line, [line.rstrip() for line in open('filename.txt', 'r')])
using System;
using System.Text;

namespace MyProgram
{
    public class Program
    {
        public static void Main(string[] args)
        {       
            using (var reader = new System.IO.StreamReader(System.IO.File.OpenRead("filename.txt"), Encoding.UTF8))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
    }
}
const fs = require('fs')

const data = fs.readFileSync('filename.txt', 'UTF-8')
const lines = data.split(/\r?\n/)
lines.forEach((line) => {
    console.log(line
})
const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
    input: fs.createReadStream('file.txt'),
    output: process.stdout,
    terminal: false
});

rl.on('line', (line) => {
    console.log(line);
});

foreach ($line in Get-Content .\filename.txt) {
    Write-Output $line
}
Const ForReading = 1
Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")

Dim file, line
Set file = fso.OpenTextFile("filename.txt", ForReading)
Do While file.AtEndOfStream = False
  line = file.ReadLine
  WScript.Echo line
Loop
file.Close

Create a new file, write text into it

So many combinations amongst various languages on handling whether the file exists or not. I’ll keep it simple here: create or overwrite.

with open('newfilename.txt', 'w') as f:
    f.write('line 1\n')
    f.write('line 2\n')
namespace MyProgram
{
    public class Program
    {
        public static void Main(string[] args)
        {       
            using (var writer = new System.IO.StreamWriter("newfilename.txt"))
            {
                writer.WriteLine("line 1");
                writer.WriteLine("line 2");
            }
        }
    }
} 
const fs = require('fs')

const writer = fs.createWriteStream('newfilename.txt')
writer.write('line 1\n')
writer.write('line 2\n')
# this will create or overwrite newfilename.txt
"line 1" | Out-File -FilePath .\newfilename.txt
Add-Content .\newfilename.txt "line 2"
# this will only create, error if already exists
New-Item .\newfilename.txt
Set-Content .\newfilename.txt "line 1"
Add-Content .\newfilename.txt "line 2"
Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")

Dim file
Set file= fso.CreateTextFile("newfilename.txt", True, False)  ' True = overwrite, False = unicode
file.WriteLine "line 1"
file.WriteLine "line 2"
file.Close

Append to an existing file

Each of these examples will create the file if it doesn’t exist, or append to it if it does – except for VB Script, which will error.

with open('priorfilename.txt', 'a') as f:
    f.write('line 3')
namespace MyProgram
{
    public class Program
    {
        public static void Main(string[] args)
        {       
            using (var writer = new System.IO.StreamWriter("priorfilename.txt", true))  // true = append
            {
                writer.WriteLine("line 3");
            }
        }
    }
}
const fs = require('fs')

const writer = fs.createWriteStream('priorfilename.txt', {'flags': 'a'})
writer.write('line 3\n')
Add-Content .\priorfilename.txt "line 3"
Const ForAppending = 8

Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")

Dim file
Set file= fso.OpenTextFile("priorfilename.txt", ForAppending)
file.WriteLine "line 3"
file.Close

Check if a file exists

import os
if os.path.exists('filename.txt'):
    print('It exists')
using System;

namespace MyProgram
{
    public class Program
    {
        public static void Main(string[] args)
        {       
            if (System.IO.File.Exists("filename.txt"))
            {
                Console.WriteLine("It exists");
            }
        }
    }
}
const fs = require('fs')

if (fs.existsSync('filename.txt')) {
    console.log('It exists')
}
If (Test-Path .\filename.txt -PathType Leaf) {
    Write-Output "It exists"
}
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

If fso.FileExists("filename.txt") Then
    WScript.Echo "It exists"
End If

By Michael Ottoson

Welcome to pointw.com. I first created this site for my personal use - literally a place for me to put stuff so I can find it wherever I go. Some of the stuff I put here might be useful to others, so I started making some of it public. Please enjoy your stay, and don't be shy in the comments.

Leave a Reply

Your email address will not be published. Required fields are marked *