Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion for emulating the open() function in Python (file handling) #1320

Closed
serge-hulne opened this issue Jul 4, 2022 · 2 comments
Closed

Comments

@serge-hulne
Copy link

serge-hulne commented Jul 4, 2022

Proposal

A simple suggestion for emulating the open() function of Python.
as in

f = open("demofile.txt", "r")
for x in f:
  print(x)

Background

Aim: Reading a file line by line in order to avoid reading a very large file all at once (to save RAM).

Workarounds

reading a file, line by line in a for loop can be done in Go the following way

func Open(fname string) (error, *os.File) {
	file, err := os.Open(fname)
	check(err)
	return err, file
}

func Close(file *os.File) {
	file.Close()
}

func ReadLines(f *os.File) chan string {
	ch_lines := make(chan string)
	go func() {
		defer close(ch_lines)
		scanner := bufio.NewScanner(f)
		for scanner.Scan() {
			ch_lines <- scanner.Text()
		}
	}()
	return ch_lines
}

Examples of use:

	_, f := fi.Open("text.txt")
	lines := fi.ReadLines(f)
        for line := range lines {
              println(line)
        }

more details here:
https://github.com/serge-hulne/goutils/blob/main/files/fileutils.go

@xushiwei
Copy link
Member

xushiwei commented Jul 5, 2022

import "os"

for line <- os.Stdin {
	println line
}

and Go+ provides builtin functions open and create for os.File.

@xushiwei
Copy link
Member

xushiwei commented Jul 5, 2022

% cat foo.gop

for line <- open("foo.gop")! {
    println line
}

% gop run foo.gop

for line <- open("foo.gop")! {
    println line
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants