Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does open with :w and :append still overwrite the file?

Tags:

string

file

io

raku

I got the following code to try out file opening and writing (without spurt):

sub MAIN {
    my $h = open 'somefile.txt', :w, :a;

    for 1..4 {
        $fh.put: "hello";
    }
    $fh.close;
}

What I expected is that with each run, it should append 4 additional lines with "hello" to the file. However it still seems to overwrite the file, after 2 or more runs there are still only 4 lines.

$ perl6 opening.p6
$ cat somefile.txt
hello
hello
hello
hello
$ perl6 opening.p6
$ cat somefile.txt
hello
hello
hello
hello

Adding or removing :a or :append doesn't seem to influence this behaviour, what am I missing?

like image 246
Jessica Nowak Avatar asked May 25 '19 05:05

Jessica Nowak


People also ask

Does W overwrite file Python?

w : Opens in write-only mode. The pointer is placed at the beginning of the file and this will overwrite any existing file with the same name. It will create a new file if one with the same name doesn't exist.

What is the difference between append and overwrite when writing data to a file?

When you open a file in append mode, the seek pointer points to the end of the file (the pointer position will be non-zero if the file is not empty). On new (empty) files, the end is equal to the beginning. So appending is the same as overwriting. So basically you are saying that there would not be any difference.

What does mode mean while working with files?

Filename is the name of the file with which we will be working on. Mode means the method in which we want to open a file & there are 4 basic modes. “r” for reading. “w” for writing. “a” for appending.


1 Answers

According to the open documentation, you want

my $h = open 'somefile.txt', :a;

The one and two-letter shorthands are not modifiers, but useable in isolation, with :w expanding to

:mode<wo>, :create, :truncate

and :a expanding to

:mode<wo>, :create, :append

mimicking POSIX.

The combination :w, :append you tried should in fact also open the file in append mode - but only after truncating it first, which doesn't seem particularly useful...

like image 141
Christoph Avatar answered Oct 10 '22 16:10

Christoph