# Create and write to a file

## Challenge

Create a new file and write the string Hello World to it.

## Restrictions

• Your challenge must write to a file on disk, in the file system.

• The file may not be a log file generated during normal operation of the interpreter.

• The file must contain only the string Hello World. It is allowed to contain a trailing newline or minimal whitespace. No other content.

• No command-line flags/pipes (etc) allowed, except when necessary to run the program. (e.g. perl -p)

## Notes

• This is , so shortest program in bytes wins.

• Follow the spirit, not the letter, of the rules.

• Is trailing newline okay? Aug 1, 2016 at 9:03
• @Winny yes, it is ok Aug 1, 2016 at 20:23
• Is a filename part of the contents of a file? Aug 12, 2016 at 20:36
• Could I also write to a magnetic tape, or must it be a disk? If so, are you including 3.5" and 5.25" disks? Or do you mean a "hard disk" or solid state disk? Nov 26, 2021 at 16:06
• @ShaunBebbers Those are acceptable too Nov 27, 2021 at 7:00

# Python 2, 32 bytes

print>>open(*"ww"),"Hello World"

• Woah. Explanation? Aug 1, 2016 at 6:22
• @DrGreenEggsandIronMan it looks like the main trick is how * can split an iterable into individual arguments in a function, so open(*"ww") becomes open("w","w"). Aug 1, 2016 at 9:09
• @ValueInk Actually the main trick is the use of the extended print statement which is rarely seen in the wild.
– xsot
Aug 1, 2016 at 10:20
• That is indeed a cool trick, but if it weren't for your *"ww" trick you'd've tied with the other Python answer here, which uses open(...).write(...) instead for the same byte count Aug 1, 2016 at 10:23
• Oops, I didn't even realise that.
– xsot
Aug 1, 2016 at 10:26

writeFile"o""Hello World"


## zsh, 17 bytes

<<<Hello\ World>x


Outputs to a file called x.

• Can you interpreted the > as a pipe? Aug 12, 2016 at 20:34
• What about >Hello\ World Aug 12, 2016 at 20:41

# Vyxal 2.5.3, 32 bytes

kh→@|;@+open(*"ww").write(VAR_)#


Vyxal can't really do anything with external files, which would normally render this challenge impossible. However, in Vyxal 2.5.3 and prior, there was an ACE exploit allowing for arbitrary Python execution. Yep, I found another one.

#### The ACE:

Vyxal is a transpiled language, so every Vyxal command is translated to some Python code, and then all of the translated commands are executed. Previously, I found that you could escape a string to insert any Python commands you wanted into the transpiled code. It turns out that you can do something similar with function names.

When defining a function in Vyxal, the resulting python looks something like this:

def FN_func(parameter_stack, arity=None):
...setup stuff...
...commands...
...finishing stuff...
return stack


When calling a function in Vyxal, the resulting Python code looks something like this:

stack += FN_func(stack)


The thing is, when parsing the name of a function, the strategy was to just read characters until reaching a :, |, or ;, which are the delimiters of different parts of the function declaration/call. This meant that you could put any characters you wanted into the name, and it would attempt to transpile it the same way.

In this case, I used a + in the function name when I called it. That results in this transpiled code:

stack += FN_+open(*"ww").write(VAR_)#(stack)


This code will error when ran, because it tries to add together a function and the None that is returned from the open command. However, even though it errors, the open command still runs, meaning that we have executed arbitrary Python. If you wanted to write longer sections of Python code, you could replace the + with ([]) and add a newline after it.

#### The program:

In this program, the payload (the arbitrary Python code) is the following:

open(*"ww").write(VAR_)


The basis of this code is the open().write() command, which creates a file named w if it doesn't exist, then writes the contents of VAR_ to it.

The VAR_ variable is set at the beginning of the Vyxal program with kh→. This pushes the builtin Hello World and saves it to the nameless variable. All variable names are prepended with VAR_ internally, so the variable VAR_ is created and contains Hello World, which is written to the newly created file. Even though this has the overhead of the ACE setup, it ends up being shorter than the Python solutions due to the builtin.

This ACE has not been fixed in the repo, but it had a patch applied server-side for the online interpreter. It was also fixed in the rewrite and subsequent 2.6 release. If you want to try out this program for yourself, you can download the 2.5.3 version here.

# Ruby, 26 bytes

Writes to file f.

open(?f,?w)<<"Hello World"


# Batch, 18 bytes

echo Hello World>f

• I think you need an @, or re-title this as (console). Oct 2, 2016 at 18:13
• The @ is not necessary. Oct 3, 2016 at 8:07
• Try saving it in a batch file and run it as such (not directly type the command). You will then see that you need the @, because the command is otherwise printed too. That means you have two options: 1) Delete this answer because it will be a dupe 2) Relabel as (console). Oct 3, 2016 at 10:35

## Batch, 19 bytes

@echo Hello World>o

• Not sure if it counts as wrong, but it outputs "Hello World" and a newline to the file, rather than simply "Hello World" Aug 1, 2016 at 12:18
• What is the '@' good for?
– PEAR
Aug 1, 2016 at 13:03
• @PEAR It prevents the command from being echoed to STDOUT.
– Neil
Aug 1, 2016 at 13:18
• @brianush1 It doesn't count as wrong, apparently. Oct 2, 2016 at 18:14

# Vim, 15 + 2 == 17 bytes

iHello World<esc>ZZ


+2 bytes for launching this with vim f instead of vim. Additionally, this version works to:

iHello World<C-o>ZZ


If launching vim like this is not allowed, there is also:

### Vim, 18 bytes

iHello World<esc>:w f<cr>


Side note: this is a polyglot. The same thing works in V, except that it is one byte shorter (since the <cr> at the end is implicit.)

• What's the  f<cr> at the end for?
– Zwei
Aug 1, 2016 at 6:05
• @Zwei 'f' is the name of the file, and the <cr> (which is a mnemonic for "enter", a single byte) is necessary to run the command. Commands that start with a colon are like a mini shell inside of vim, and the command :w is the command for writing to a file. Aug 1, 2016 at 6:08
• Should <esc> not be counted as 5 bytes and <cr> as 4, since they have to be fully typed in? Aug 3, 2016 at 5:38
• @BartvanNierop No, <esc> is just notation for "The escape key", which is 0x1B, and <cr> is notation for "The Carriage Return key" which is 0x0B Aug 3, 2016 at 5:39
• Well first off, there is a precedent to score vim with keystrokes == bytes, but second off, there are several ways to write this in vim "code" without using the vim-key notation. For example, if you use <C-v> to insert a literal escape character and a literal carriage return, then you can assign all of these strokes to a macro, and run it that way. You could also do it in vimscript with normal 'iHello World^[:w f^M which is how vim displays it, not how you enter it. ^[ and ^M are both one byte. Aug 3, 2016 at 5:50

# C, 44 bytes

main(){fputs("Hello World",fopen("o","w"));}

• This will segfault on some systems without #include <stdio.h> Aug 1, 2016 at 12:23
• @StevenPenny As long as there's a system/compiler where it's guaranteed not to segfault, that's fine. Answers generally don't have to be portable. Oct 2, 2016 at 20:57
• @StevenPenny And now it has.
– orlp
Oct 3, 2016 at 5:54

# Dyalog APL, 19 bytes

⎕NPUT⍨'Hello World'


Creates a file with the name and contents "Hello World".

# PowerShell, 15 bytes

"Hello World">o


> redirects the string to a file called o in the current directory.

# Node.js, 42 bytes

require("fs").writeFile('o','Hello World')


i don't think this needs explanation

# Node.js REPL, 31 bytes

fs.writeFile('o','Hello World')


for some reason in repl you dont need to include fs

• I don't think this works. In order for it to work, you'd need require("fs").writeFile("o","Hello World"). Otherwise, fs is not included. Aug 1, 2016 at 19:45
• @CᴏɴᴏʀO'Bʀɪᴇɴ huh ok. works in REPL for some reason Aug 1, 2016 at 19:49
• I beat you with 1 byte :P Nov 27, 2021 at 15:40

## Bash, 18 bytes

echo Hello World>a


## Pyth, 14 bytes

.w"Hello World


Outputs to a file called o.txt.

# ed, 19 characters

i
Hello World
.
w o


Sample run:

bash-4.3$ed <<<$'i\nHello World\n.\nw o'
12

bash-4.3$cat o Hello World  # MATL, 15 bytes 'Hello World'Z#  This creates a file called inout and writes the string to it. ## K, 20 Bytes  :f 0:,"Hello World" :f  Confirmation;  mmm@chromozorz:~/q$ cat f.txt
Hello World

• Since nobody said it yet, welcome to Programming Puzzles & Code Golf. Oct 2, 2016 at 18:19
• Much appreciated! Oct 5, 2016 at 19:54
• OK. I also think that you have extra leading spaces though. I will edit the spaces out if you want (I don't know if they are intentionally placed, but I think it was unintentional.) Oct 6, 2016 at 5:22

# Clojure, 23 bytes

#(spit"x""Hello World")


Anonymous function which creates file called x and writes Hello World there.

# C#, 9377 76 bytes

using System.IO;namespace N{class C{static void M(){File.WriteAllText("f", "Hello World");}}}

class C{static void Main(){System.IO.File.WriteAllText("f", "Hello World");}}

class C{static void Main(){System.IO.File.WriteAllText("f","Hello World");}}


See it work, with an exception for unauthorized file access.

## Changelog

### Rev2

• Removed unnecessary namespace
• Changed function name to Main (because otherwise it won't be detected as main function)
• Removed using directive (thanks Jean Lourenço)

### Rev3

• Removed space that sneaked in.

# C# (without boilerplate), 47 bytes

void M(){File.WriteAllText("f","Hello World");}

• You can save some bytes by removing the using and appending it directly to the method: System.IO.File.WriteAllText[...] Aug 2, 2016 at 11:26
• @JeanLourenço Thanks. I had that originally and then changed it for reasons unknown. Aug 2, 2016 at 14:15

# R, 3836 35 bytes

sink(" ");cat("Hello World");sink()


I like how the created file has no name ! It's just .txt anything, in fact !

-2 bytes thanks to @PEAR remark !
-1 bytes thanks to @BartvanNierop !

This code will produce a file with no name.

• Is the '.txt' really necessary? File endings are just for the user. A single character might me enough.
– PEAR
Aug 1, 2016 at 13:02
• I don't know R, but could you not shave off another byte, as by @PEAR's suggestion, by simply naming the file "a"? Aug 3, 2016 at 5:35

# Python, 34 bytes

open("h","w").write("Hello World")


Outputs to a file called h.

# APLX, 15 bytes

'Hello World'⍈1


Creates an APL component file containing just one component; the desired string. It can be read back with:

      'Hello World'⍇1
Hello World


# Gema, 28 characters

\A=@write{o;Hello World}@end


Sample run:

bash-4.3$gema '\A=@write{o;Hello World}@end' bash-4.3$ cat o
Hello World


# Racket, 43 bytes

(display"Hello World"(open-output-file"f"))


# Julia, 47 bytes

f=open("o","w");write(f,"Hello World");close(f)


I tried using writedlm, but it didn't work out.

# C, 37 bytes

main(){system("echo Hello World>o");}


# Perl 6,  27  23 bytes

'o'.IO.spurt: 'Hello World'
spurt 'o','Hello World'

# Java 7, 100 95 bytes

void f()throws Exception{java.io.Writer p=new java.io.PrintWriter("x");p.print("Hello World");}


Or if you want to close the writer after using it (101 bytes):

void f()throws Exception{try(java.io.Writer p=new java.io.PrintWriter("x")){p.print("Hello World");}}


Ungolfed:

class Main{
static void f() throws Exception{
try(java.io.Writer p = new java.io.PrintWriter("x")){
p.print("Hello World");
}
}

public static void main(String[] a){
try{
f();
} catch(Exception ex){
}
}
}


Usage:

java -jar Main.jar

• Java is my favorite language but jesus christ it's hilarious how bad a golfing language it is haha Aug 1, 2016 at 11:44
• @AlanTuning Indeed. xD I work with Java at work, and it's fun to code-golf in Java. You will NEVER be able to win a code-golf challenge here using Java, but it's still fun to write the Java code as short as possible. Aug 1, 2016 at 12:02
• well, you can just void f()throws Exception{new java.io.PrintWriter("x").print("Hello World");} Aug 1, 2016 at 15:13
• java.io.Writer p=new java.io.PrintWriter saves you some more characters. Aug 1, 2016 at 18:39
• @cliffroot Hmm, I tried that initially, but it didn't seem to write anything to disk. Will try again tomorrow, currently I don't have an IDE and file I/O doesn't work in ideone. Aug 1, 2016 at 19:26

# eacal, 26 bytes

write a string Hello World


This writes a string Hello World to file a, creating it if not present. Basically:

write <fileName> <exec>


and

string <params to convert to string>


Run the program as:

λ node eacal.js writeFile


# J, 21 bytes

'Hello World'1!:3<'o'


This writes to a file o in the current directory, or, if not called from a file, in your j64-804 file. 1!:3 is the write foreign, and <'o' is the boxed filename (filenames need to be boxed). The LHS is the string to write.