Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2024/25/2
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Scala


[ edit | logout ]
[ sandbox | passwd ]

Reading a text file; writing to a text file

(1) reading a text file line by line
def main():
    f = open("input.txt", "r")

    for line in f:
        line = line.rstrip("\r\n")
        print(line)

    f.close()
import std.stdio;

void main()
{
    File f = File("input.txt", "r");

    foreach (line; f.byLineCopy())
    {
        // line doesn't contain the newline character
        writeln(line);
    }

    // f.close();
}

In D, when the variable f goes out of scope, it's guaranteed that the file will be closed. Thus, calling f.close() is not necessary. But, you can call it if you want. For instance, if you want to re-open a file, then first you'll have to close it manually and then you can open it again.

f.byLineCopy() returns a string copy of the current line that can be stored.

f.byLine() returns a slice on the inner buffer whose content changes as you read the lines. It's faster but line is only valid in the current iteration, you cannot store it. byLineCopy() is more secure.

(2) writing to a text file
def main():
    f = open("out.txt", "w")

    print("Hello, World!", file=f)
    year = 2025
    print(f"Current year: {year}", file=f)

    print("END")
import std.stdio;

void main()
{
    File f = File("out.txt", "w");

    f.writeln("Hello, World!");
    int year = 2025;
    f.writefln("Current year: %s", year);

    // f.close();

    writeln("END");
}
$ cat out.txt
Hello, World!
Current year: 2025
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2025 June 28, 17:45