How to Create a File and Write to It

How do I create a file and write to it?

Note that each of the code samples below may throw IOException. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.

Note that each of the code samples below will overwrite the file if it already exists

Creating a text file:

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

Creating a binary file:

byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();

Java 7+ users can use the Files class to write to files:

Creating a text file:

List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Creating a binary file:

byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);

Writing to a new file if it doesn't exist, and appending to a file if it does

It's not clear to me exactly where the high-score that you're interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the "try/except".

import os
player = 'bob'

filename = player+'.txt'

if os.path.exists(filename):
append_write = 'a' # append if already exists
else:
append_write = 'w' # make a new file if not

highscore = open(filename,append_write)
highscore.write("Username: " + player + '\n')
highscore.close()

Creating a Txt-File and write to it

You don't actually have to check if the file exists, as StreamWriter will do that for you.

using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(TextBox1.Text);
}

public StreamWriter(
string path,
bool append
)

Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.

How to create text file and write to it in vbscript

Simple Google search like "vbscript create and write to text file" will give you ocean of information on how to tackle this. Anyway here is simplest one to give you kick start.

'~ Create a FileSystemObject
Set objFSO=CreateObject("Scripting.FileSystemObject")

'~ Provide file path
outFile="YouFolderPath\Results.txt"

'~ Setting up file to write
Set objFile = objFSO.CreateTextFile(outFile,True)


strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colFiles = objWMIService.ExecQuery _
("Select * from CIM_DataFile Where Extension = 'mdb' OR Extension = 'ldb'")

For Each obj_File in colFiles
'Wscript.Echo objFile.Name 'Commented out

'~ Write to file
objFile.WriteLine obj_File.Name
Next

'~ Close the file
objFile.Close

How to create a new text file using Python

Looks like you forgot the mode parameter when calling open, try w:

with open("copy.txt", "w") as file:
file.write("Your text goes here")

The default value is r and will fail if the file does not exist

'r' open for reading (default)
'w' open for writing, truncating the file first

Other interesting options are

'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists

See Doc for Python2.7 or Python3.6

Create text file and fill it using bash

If you're wanting this as a script, the following Bash script should do what you want (plus tell you when the file already exists):

#!/bin/bash
if [ -e $1 ]; then
echo "File $1 already exists!"
else
echo >> $1
fi

If you don't want the "already exists" message, you can use:

#!/bin/bash
if [ ! -e $1 ]; then
echo >> $1
fi

Edit about using:

Save whichever version with a name you like, let's say "create_file" (quotes mine, you don't want them in the file name). Then, to make the file executatble, at a command prompt do:

chmod u+x create_file

Put the file in a directory in your path, then use it with:

create_file NAME_OF_NEW_FILE

The $1 is a special shell variable which takes the first argument on the command line after the program name; i.e. $1 will pick up NAME_OF_NEW_FILE in the above usage example.

How to create text file using Groovy?

new File(path) means create pointer to file or directory with selected path.
Using this pointer you can do anything what you want create, read, append etc.
If you wish to only create file on drive you can do:

def newFile = new File("C:/Users/ramus/Documents/Jars/test.txt")
newFile.createNewFile()

open() in Python does not create a file if it doesn't exist

You should use open with the w+ mode:

file = open('myfile.dat', 'w+')


Related Topics



Leave a reply



Submit