Bro*_*olf 127 language-agnostic file-io programming-languages
这必须是所有程序员不时有的常见问题.如何从文本文件中读取一行?然后下一个问题是我如何写回来.
当然,大多数人在日常编程中都使用高级框架(可以在答案中使用)但有时候知道如何在较低级别进行编程也很好.
我自己知道该怎么做的C,C++以及Objective-C,但它肯定会得心应手,看看它是如何在所有流行的语言来完成,如果仅仅是为了帮助我们做出什么语言来尽我们的文件IO在一个更好的决定.特别是我认为这将是有趣的,看看它是如何在字符串操作语言完成,如:python,ruby当然perl.
所以我想在这里我们可以创建一个社区资源,我们可以为我们的配置文件加注星标,并参考我们何时需要以某种新语言进行文件I/O. 更不用说曝光我们都会得到我们日常不处理的语言.
这是你需要回答的方式:
澄清:
对语言没有特别限制.
C,C++,C#,Java,Objective-C都是伟大的.
如果你知道如何做到这一点的Prolog,Haskell,Fortran,Lisp,或Basic则请请便.
Dan*_*ita 242
规格至少可以说是粗略的,但我尽我所能.让downvoting开始吧!:)我仍然觉得这是一个有趣的运动.
HAI
CAN HAS STDIO?
PLZ OPEN FILE "FILEIO.TXT" ITZ "TehFilez"?
AWSUM THX
BTW #There is no standard way to output to files yet...
VISIBLE "Hello" ON TehFilez
BTW #There isn't a standard way to append to files either...
MOAR VISIBLE "World" ON TehFilez
GIMMEH LINES TehLinez OUTTA TehFilez
I HAS A SecondLine ITZ 1 IN MAH TehLinez
VISIBLE SecondLine
O NOES
VISIBLE "OH NOES!!!"
KTHXBYE
Run Code Online (Sandbox Code Playgroud)
sna*_*ile 48
with open('fileio.txt', 'w') as f:
f.write('hello')
with open('fileio.txt', 'a') as f:
f.write('\nworld')
with open('fileio.txt') as f:
s = f.readlines()[1]
print(s)
Run Code Online (Sandbox Code Playgroud)
澄清
readlines()返回文件中所有行的列表.因此,readlines()的调用导致读取文件的每一行.在那种特殊情况下,使用readlines()是很好的,因为我们必须要读取整个文件(我们想要它的最后一行).但是如果我们的文件包含很多行而我们只想打印它的第n行,则不必读取整个文件.下面是一些在Python中获取文件第n行的更好方法:什么替代Python 3中的xreadlines()?.
这是什么声明?with语句启动一个代码块,您可以在其中使用变量f作为从open()调用返回的流对象.当with块结束时,python会自动调用f.close().这可以保证在退出with块时关闭文件,无论您何时或何时退出块(即使您通过未处理的异常退出).您可以显式调用f.close(),但是如果您的代码引发异常而您没有进入f.close()调用该怎么办?这就是with语句有用的原因.
在每次操作之前,您无需重新打开文件.你可以用块来编写整个代码.
with open('fileio.txt', 'w+') as f:
f.write('hello')
f.write('\nworld')
s = f.readlines()[1]
print(s)
Run Code Online (Sandbox Code Playgroud)
我用三个块来强化三个操作之间的区别:写(模式'w'),追加(模式'a'),读(模式'r',默认).
Svi*_*ack 43
,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]
Run Code Online (Sandbox Code Playgroud)
Mar*_*lin 42
因为没有其他人......
IDENTIFICATION DIVISION.
PROGRAM-ID. WriteDemo.
AUTHOR. Mark Mullin.
* Hey, I don't even have a cobol compiler
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD TestFile.
01 TestData.
02 LineNum PIC X.
02 LineText PIC X(72).
PROCEDURE DIVISION.
Begin.
OPEN OUTPUT TestFile
DISPLAY "This language is still around."
PERFORM GetFileDetails
PERFORM UNTIL TestData = SPACES
WRITE TestData
PERFORM GetStudentDetails
END-PERFORM
CLOSE TestFile
STOP RUN.
GetFileDetails.
DISPLAY "Enter - Line number, some text"
DISPLAY "NXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
ACCEPT TestData.
Run Code Online (Sandbox Code Playgroud)
Ion*_*tan 39
main :: IO ()
main = let filePath = "fileio.txt" in
do writeFile filePath "hello"
appendFile filePath "\nworld"
fileLines <- readFile filePath
let secondLine = (lines fileLines) !! 1
putStrLn secondLine
Run Code Online (Sandbox Code Playgroud)
如果您只想读/写文件:
main :: IO ()
main = readFile "somefile.txt" >>= writeFile "someotherfile.txt"
Run Code Online (Sandbox Code Playgroud)
Ber*_*ard 35
module d_io;
import std.stdio;
void main()
{
auto f = File("fileio.txt", "w");
f.writeln("hello");
f.writeln("world");
f.open("fileio.txt", "r");
f.readln;
auto s = f.readln;
writeln(s);
}
Run Code Online (Sandbox Code Playgroud)
Way*_*rad 34
PATH = 'fileio.txt'
File.open(PATH, 'w') { |file| file.puts "hello" }
File.open(PATH, 'a') { |file| file.puts "world" }
puts line = File.readlines(PATH).last
Run Code Online (Sandbox Code Playgroud)
Las*_*olt 33
string path = "fileio.txt";
File.WriteAllLines(path, new[] { "hello"}); //Will end it with Environment.NewLine
File.AppendAllText(path, "world");
string secondLine = File.ReadLines(path).ElementAt(1);
Console.WriteLine(secondLine);
Run Code Online (Sandbox Code Playgroud)
File.ReadLines(path).ElementAt(1)仅限.Net 4.0,替代方案是File.ReadAllLines(path)[1]将整个文件解析为数组.
Mai*_*ter 29
ANSI C
#include <stdio.h>
#include <stdlib.h>
int /*ARGSUSED*/
main(char *argv[0], int argc) {
FILE *file;
char buf[128];
if (!(file = fopen("fileio.txt", "w")) {
perror("couldn't open for writing fileio.txt");
exit(1);
}
fprintf(file, "hello");
fclose(file);
if (!(file = fopen("fileio.txt", "a")) {
perror("couldn't opened for appening fileio.txt");
exit(1);
}
fprintf(file, "\nworld");
fclose(file);
if (!(file = fopen("fileio.txt", "r")) {
perror("couldn't open for reading fileio.txt");
exit(1);
}
fgets(buf, sizeof(buf), file);
fgets(buf, sizeof(buf), file);
fclose(file);
puts(buf);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 29
#!/bin/sh
echo "hello" > fileio.txt
echo "world" >> fileio.txt
LINE=`sed -ne2p fileio.txt`
echo $LINE
Run Code Online (Sandbox Code Playgroud)
实际上该sed -n "2p"部分打印第二行,但问题是要求第二行存储在变量中然后打印,所以... :)
小智 27
我没有在7年内触及asm,所以我不得不使用谷歌一起破解这个,但仍然,它有效;)我知道它不是100%正确,但嘿:D
好的,它不起作用.抱歉,这个.虽然它world最后打印,但它不会从文件中打印出来,而是从第ecx27行设置.
section .data
hello db 'hello',10
helloLen equ $-hello
world db 'world',10
worldLen equ $-world
helloFile db 'hello.txt'
section .text
global _start
_start:
mov eax,8
mov ebx,helloFile
mov ecx,00644Q
int 80h
mov ebx,eax
mov eax,4
mov ecx, hello
mov edx, helloLen
int 80h
mov eax,4
mov ecx, world
mov edx, worldLen
int 80h
mov eax,6
int 80h
mov eax,5
mov ebx,helloFile
int 80h
mov eax,3
int 80h
mov eax,4
mov ebx,1
int 80h
xor ebx,ebx
mov eax,1
int 80h
Run Code Online (Sandbox Code Playgroud)
使用的参考文献:http: //www.cin.ufpe.br/~if817/arquivos/asmtut/quickstart.html
http://bluemaster.iu.hio.no/edu/dark/lin-asm/syscalls.html
http://www.digilife.be/quickreferences/QRC/LINUX%20System%20Call%20Quick%20Reference.pdf
Ion*_*tan 21
首先,许多嵌套回调.
var fs = require("fs");
var sys = require("sys");
var path = "fileio.txt";
fs.writeFile(path, "hello", function (error) {
fs.open(path, "a", 0666, function (error, file) {
fs.write(file, "\nworld", null, "utf-8", function () {
fs.close(file, function (error) {
fs.readFile(path, "utf-8", function (error, data) {
var lines = data.split("\n");
sys.puts(lines[1]);
});
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
有点清洁:
var writeString = function (string, nextAction) {
fs.writeFile(path, string, nextAction);
};
var appendString = function (string, nextAction) {
return function (error, file) {
fs.open(path, "a", 0666, function (error, file) {
fs.write(file, string, null, "utf-8", function () {
fs.close(file, nextAction);
});
});
};
};
var readLine = function (index, nextAction) {
return function (error) {
fs.readFile(path, "utf-8", function (error, data) {
var lines = data.split("\n");
nextAction(lines[index]);
});
};
};
var writeToConsole = function (line) {
sys.puts(line);
};
writeString("hello", appendString("\nworld", readLine(1, writeToConsole)));
Run Code Online (Sandbox Code Playgroud)
Chr*_*ris 21
(defun main ()
(with-open-file (s "fileio.txt" :direction :output :if-exists :supersede)
(format s "hello"))
(with-open-file (s "fileio.txt" :direction :io :if-exists :append)
(format s "~%world")
(file-position s 0)
(loop repeat 2 for line = (read-line s nil nil) finally (print line))))
Run Code Online (Sandbox Code Playgroud)
Abh*_*kar 18
(use '[clojure.java.io :only (reader)])
(let [file-name "fileio.txt"]
(spit file-name "hello")
(spit file-name "\nworld" :append true)
(println (second (line-seq (reader file-name)))))
Run Code Online (Sandbox Code Playgroud)
或者等效地,使用线程宏->(也称为paren remover):
(use '[clojure.java.io :only (reader)])
(let [file-name "fileio.txt"]
(spit file-name "hello")
(spit file-name "\nworld" :append true)
(-> file-name reader line-seq second println))
Run Code Online (Sandbox Code Playgroud)
Las*_*olt 18
sc fileio.txt 'hello'
ac fileio.txt 'world'
$line = (gc fileio.txt)[1]
$line
Run Code Online (Sandbox Code Playgroud)
Bri*_*ell 18
下面是使用只是内置命令,而不是调用外部命令,如shell脚本sed或tail作为先前的响应已完成.
#!/bin/sh
echo hello > fileio.txt # Print "hello" to fileio.txt
echo world >> fileio.txt # Print "world" to fileio.txt, appending
# to what is already there
{ read input; read input; } < fileio.txt
# Read the first two lines of fileio.txt,
# storing the second in $input
echo $input # Print the contents of $input
Run Code Online (Sandbox Code Playgroud)
在编写重要的shell脚本时,建议尽可能使用内置函数,因为生成一个单独的进程可能会很慢; 通过在我的机器上进行快速测试,该sed解决方案比使用速度慢约20倍read.如果你打算打电话sed一次,就像在这种情况下一样,它并不重要,因为它会比你注意到的更快地执行,但是如果你要执行数百或数千次,它可以加起来.
对于那些不熟悉的语法,{并} 执行命令的列表在当前shell环境(相对于(和)其创建子外壳;我们需要在当前外壳环境中操作,因此,我们稍后可以使用变量的值) .我们需要将命令组合在一起,以使它们都在相同的输入流上操作,通过重定向来创建fileio.txt; 如果我们只是简单地运行read < fileio.txt; read input < fileio.txt,我们就会得到第一行,因为文件将被关闭并在两个命令之间重新打开.由于shell语法的特殊性({并且}是保留字,而不是元字符),我们需要分离{和}从带有空格的其余命令开始,并用a终止命令列表;.
该read内置带一个参数变量的名字读入.它消耗了一行输入,打破了空格的输入(从技术上讲,它根据内容突破它$IFS,默认为空格字符,空格字符意味着将它分隔在任何空格,制表符或换行符上),指定每个单词以顺序给出的变量名称,并将该行的其余部分分配给最后一个变量.因为我们只提供一个变量,所以它只是将整行放在该变量中.我们重用$input变量,因为我们不关心第一行是什么(如果我们使用Bash,我们可能不提供变量名,但为了便携,你必须始终提供至少一个名称).
请注意,虽然您可以像我一样一次读取一行,但更常见的模式是将其包装在while循环中:
while read foo bar baz
do
process $foo $bar $baz
done < input.txt
Run Code Online (Sandbox Code Playgroud)
Las*_*olt 17
let path = "fileio.txt"
File.WriteAllText(path, "hello")
File.AppendAllText(path, "\nworld")
let secondLine = File.ReadLines path |> Seq.nth 1
printfn "%s" secondLine
Run Code Online (Sandbox Code Playgroud)
cas*_*nca 16
我差不多10年没用过BASIC了,但这个问题让我有理由快速提升自己的知识水平.:)
OPEN "fileio.txt" FOR OUTPUT AS 1
PRINT #1, "hello"
PRINT #1, "world"
CLOSE 1
OPEN "fileio.txt" FOR INPUT AS 1
LINE INPUT #1, A$
LINE INPUT #1, A$
CLOSE 1
PRINT A$
Run Code Online (Sandbox Code Playgroud)
Bro*_*olf 16
NSFileHandle *fh = [NSFileHandle fileHandleForUpdatingAtPath:@"fileio.txt"];
[[NSFileManager defaultManager] createFileAtPath:@"fileio.txt" contents:nil attributes:nil];
[fh writeData:[@"hello" dataUsingEncoding:NSUTF8StringEncoding]];
[fh writeData:[@"\nworld" dataUsingEncoding:NSUTF8StringEncoding]];
NSArray *linesInFile = [[[NSString stringWithContentsOfFile:@"fileio.txt"
encoding:NSUTF8StringEncoding
error:nil] stringByStandardizingPath]
componentsSeparatedByString:@"\n"];
NSLog(@"%@", [linesInFile objectAtIndex:1]);
Run Code Online (Sandbox Code Playgroud)
Viv*_*ath 16
#!/usr/bin/env perl
use 5.10.0;
use utf8;
use strict;
use autodie;
use warnings qw< FATAL all >;
use open qw< :std :utf8 >;
use English qw< -no_match_vars >;
# and the last shall be first
END { close(STDOUT) }
my $filename = "fileio.txt";
my($handle, @lines);
$INPUT_RECORD_SEPARATOR = $OUTPUT_RECORD_SEPARATOR = "\n";
open($handle, ">", $filename);
print $handle "hello";
close($handle);
open($handle, ">>", $filename);
print $handle "world";
close($handle);
open($handle, "<", $filename);
chomp(@lines = <$handle>);
close($handle);
print STDOUT $lines[1];
Run Code Online (Sandbox Code Playgroud)
Ion*_*tan 15
<?php
$filePath = "fileio.txt";
file_put_contents($filePath, "hello");
file_put_contents($filePath, "\nworld", FILE_APPEND);
$lines = file($filePath);
echo $lines[1];
// closing PHP tags are bad practice in PHP-only files, don't use them
Run Code Online (Sandbox Code Playgroud)
st0*_*0le 15
import java.io.*;
import java.util.*;
class Test {
public static void main(String[] args) throws IOException {
String path = "fileio.txt";
File file = new File(path);
//Creates New File...
try (FileOutputStream fout = new FileOutputStream(file)) {
fout.write("hello\n".getBytes());
}
//Appends To New File...
try (FileOutputStream fout2 = new FileOutputStream(file,true)) {
fout2.write("world\n".getBytes());
}
//Reading the File...
try (BufferedReader fin = new BufferedReader(new FileReader(file))) {
fin.readLine();
System.out.println(fin.readLine());
}
}
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*d F 15
cat("hello\n", file="fileio.txt")
cat("world\n", file="fileio.txt", append=TRUE)
line2 = readLines("fileio.txt", n=2)[2]
cat(line2)
Pot*_*ter 14
#include <limits>
#include <string>
#include <fstream>
#include <iostream>
int main() {
std::fstream file( "fileio.txt",
std::ios::in | std::ios::out | std::ios::trunc );
file.exceptions( std::ios::failbit );
file << "hello\n" // << std::endl, not \n, if writing includes flushing
<< "world\n";
file.seekg( 0 )
.ignore( std::numeric_limits< std::streamsize >::max(), '\n' );
std::string input_string;
std::getline( file, input_string );
std::cout << input_string << '\n';
}
Run Code Online (Sandbox Code Playgroud)
或者有点不那么迂腐
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main() {
fstream file( "fileio.txt", ios::in | ios::out | ios::trunc );
file.exceptions( ios::failbit );
file << "hello" << endl
<< "world" << endl;
file.seekg( 0 ).ignore( 10000, '\n' );
string input_string;
getline( file, input_string );
cout << input_string << endl;
}
Run Code Online (Sandbox Code Playgroud)
小智 13
package main
import (
"os"
"bufio"
"log"
)
func main() {
file, err := os.Open("fileio.txt", os.O_RDWR | os.O_CREATE, 0666)
if err != nil {
log.Exit(err)
}
defer file.Close()
_, err = file.Write([]byte("hello\n"))
if err != nil {
log.Exit(err)
}
_, err = file.Write([]byte("world\n"))
if err != nil {
log.Exit(err)
}
// seek to the beginning
_, err = file.Seek(0,0)
if err != nil {
log.Exit(err)
}
bfile := bufio.NewReader(file)
_, err = bfile.ReadBytes('\n')
if err != nil {
log.Exit(err)
}
line, err := bfile.ReadBytes('\n')
if err != nil {
log.Exit(err)
}
os.Stdout.Write(line)
}
Run Code Online (Sandbox Code Playgroud)
clo*_*esh 12
可能不是最惯用的Erlang,但是:
#!/usr/bin/env escript
main(_Args) ->
Filename = "fileio.txt",
ok = file:write_file(Filename, "hello\n", [write]),
ok = file:write_file(Filename, "world\n", [append]),
{ok, File} = file:open(Filename, [read]),
{ok, _FirstLine} = file:read_line(File),
{ok, SecondLine} = file:read_line(File),
ok = file:close(File),
io:format(SecondLine).
Run Code Online (Sandbox Code Playgroud)
tar*_*ius 12
尽管有些人说Emacs主要是文本编辑器[1].因此,虽然Emacs Lisp可用于解决各种问题,但它可以针对文本编辑器的需求进行优化.由于文本编辑器(显然)在处理文件的方式方面有非常特殊的需求,这会影响Emacs Lisp提供的文件相关功能.
基本上这意味着Emacs Lisp不提供以文件形式打开文件的功能,并逐个阅读.同样,如果不先加载整个文件,就无法附加到文件中.而是将文件完全[2]读入缓冲区[3],进行编辑,然后再次保存到文件中.
对于必须完成的任务,你可以使用Emacs Lisp这是合适的,如果你想做一些不涉及编辑的东西,可以使用相同的功能.
如果你想一遍又一遍地附加到一个文件,这会带来巨大的开销,但这可能如此处所示.在实践中,您通常在写入文件之前手动或以编程方式完成对缓冲区的更改(只需在下面的示例中组合前两个s表达式).
(with-temp-file "file"
(insert "hello\n"))
(with-temp-file "file"
(insert-file-contents "file")
(goto-char (point-max))
(insert "world\n"))
(with-temp-buffer
(insert-file-contents "file")
(next-line)
(message "%s" (buffer-substring (point) (line-end-position))))
Run Code Online (Sandbox Code Playgroud)
[1]至少我不会把它称为操作系统; 替代UI是,操作系统没有.
[2]您只能加载文件的一部分,但这只能按字节指定.
[3]缓冲区既是某种类似于字符串的数据类型,也是"编辑文件时看到的东西".虽然编辑缓冲区显示在窗口中,但缓冲区不一定必须对用户可见.
编辑:如果要查看插入缓冲区的文本,您显然必须使其可见,并在操作之间休眠.因为Emacs通常只在等待用户输入时重新显示屏幕(并且睡眠与等待输入不同),您还必须强制重新显示.在这个例子中这是必要的(使用它代替第二个性别); 在实践中,我甚至不必使用"重新显示" - 所以是的,这很难看,但......
(with-current-buffer (generate-new-buffer "*demo*")
(pop-to-buffer (current-buffer))
(redisplay)
(sleep-for 1)
(insert-file-contents "file")
(redisplay)
(sleep-for 1)
(goto-char (point-max))
(redisplay)
(sleep-for 1)
(insert "world\n")
(redisplay)
(sleep-for 1)
(write-file "file"))
Run Code Online (Sandbox Code Playgroud)
The*_*eLQ 11
@echo off
echo hello > fileio.txt
echo world >> fileio.txt
set /P answer=Insert:
echo %answer% >> fileio.txt
for /f "skip=1 tokens=*" %%A in (fileio.txt) do echo %%A
Run Code Online (Sandbox Code Playgroud)
为了解释最后一个可怕的寻找循环,它假设文件中只有hello(换行符)世界.所以它只是跳过第一行,只回过第二行.
更新日志
小智 11
new File("fileio.txt").with {
write "hello\n"
append "world\n"
println secondLine = readLines()[1]
}
Run Code Online (Sandbox Code Playgroud)
mis*_*tor 11
使用标准库:
val path = "fileio.txt"
val fout = new FileWriter(path)
fout write "hello\n"
fout.close()
val fout0 = new FileWriter(path, true)
fout0 write "world\n"
fout0.close()
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)
Run Code Online (Sandbox Code Playgroud)
使用Josh Suereth的Scala-ARM库:
val path = "fileio.txt"
for(fout <- managed(new FileWriter(path)))
fout write "hello\n"
for(fout <- managed(new FileWriter(path, true)))
fout write "world\n"
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)
Run Code Online (Sandbox Code Playgroud)
由于很多人使用相同的文件描述符来编写两个字符串,所以我在答案中也包含了这种方式.
使用标准库:
val path = "fileio.txt"
val fout = new FileWriter(path)
fout write "hello\n"
fout write "world\n"
fout.close()
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)
Run Code Online (Sandbox Code Playgroud)
使用Josh Suereth的Scala-ARM库:
val path = "fileio.txt"
for(fout <- managed(new FileWriter(path))){
fout write "hello\n"
fout write "world\n"
}
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)
Run Code Online (Sandbox Code Playgroud)
Gra*_*hiu 10
Rebol []
write/lines %fileio.txt "hello"
write/lines/append %fileio.txt "world"
print last read/lines %fileio.txt
Run Code Online (Sandbox Code Playgroud)
对于如何做这种事情的例子很多语言(61!)尝试对文件I/O页面罗塞塔代码.公平地说,它似乎并没有准确地回答你所要求的 - 它正在处理整个文件I/O--但它非常接近并且覆盖范围更广,否则这个问题可能会作为答案吸引.
德尔福,标准,低级方式(即没有TStringList和其他玩具):
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
f: Text;
fn: string;
ln: string;
begin
fn := ExtractFilePath(ParamStr(0)) + 'fileio.txt';
// Create a new file
FileMode := fmOpenWrite;
AssignFile(f, fn);
try
Rewrite(f);
Writeln(f, 'hello');
Writeln(f, 'world');
finally
CloseFile(f);
end;
// Read from the file
FileMode := fmOpenRead;
AssignFile(f, fn);
try
Reset(f);
Readln(f, ln);
Readln(f, ln);
Writeln(ln);
finally
CloseFile(f);
end;
end.
Run Code Online (Sandbox Code Playgroud)
因为Delphi是本机Win32编译器,所以您也可以使用Windows API来处理所有I/O操作:
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils, Windows;
var
f: HFILE;
fn: string;
lns: AnsiString;
fsize, amt, i: cardinal;
AfterLine1: boolean;
const
data = AnsiString('hello'#13#10'world');
begin
fn := ExtractFilePath(ParamStr(0)) + 'fileio.txt';
f := CreateFile(PChar(fn), GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
try
WriteFile(f, data, length(data), amt, nil);
finally
CloseHandle(f);
end;
f := CreateFile(PChar(fn), GENERIC_READ, 0, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
try
fsize := GetFileSize(f, nil);
SetLength(lns, fsize);
ReadFile(f, lns[1], fsize, amt, nil);
for i := 1 to fsize do
case lns[i] of
#10: AfterLine1 := true;
else
if AfterLine1 then
Write(lns[i]);
end;
finally
CloseHandle(f);
end;
end.
Run Code Online (Sandbox Code Playgroud)
而且,为了完整起见,我包括了高级方法,即使我自己从不使用它:
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes;
var
fn: string;
begin
fn := ExtractFilePath(ParamStr(0)) + 'fileio.txt';
with TStringList.Create do
try
Add('hello');
Add('world');
SaveToFile(fn);
finally
Free;
end;
with TStringList.Create do
try
LoadFromFile(fn);
Writeln(Strings[1]);
finally
Free;
end;
end.
Run Code Online (Sandbox Code Playgroud)
使用Adobe AIR库:
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
public class fileio
{
public static function doFileIO():void
{
var file:File = File.applicationStorageDirectory.resolvePath("fileio.txt");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.writeUTFBytes("hello");
stream.writeUTFBytes("\nworld");
stream.close();
stream.open(file, FileMode.READ);
var content:String = stream.readUTFBytes(stream.bytesAvailable);
stream.close();
var input:String = content.split("\n")[1];
trace(input);
}
}
Run Code Online (Sandbox Code Playgroud)
由于安全原因,AIR应用程序无法写入其目录,因此它使用应用程序存储目录.
有关更多信息(以及下载最新版本):
USING: io io.encodings.utf8 io.files ;
"fileio.txt" utf8
[ [ "hello" print ] with-file-writer ]
[ [ "world" print ] with-file-appender ]
[ file-lines last print ] 2tri
Run Code Online (Sandbox Code Playgroud)
use v6;
my $path = 'fileio.txt';
# Open $path for writing.
given open($path, :w) {
.say('hello'); # Print the line "hello\n" to it.
.close; # Close the file.
}
# Open the file for appending.
given open($path, :a) {
.say('world'); # Append the line "world\n" to it.
.close;
}
my $line = lines($path)[1]; # Get the second line. lines returns a lazy iterator.
say $line; # Perl 6 filehandles autochomp, so we use say to add a newline.
Run Code Online (Sandbox Code Playgroud)
编辑:这是一个带有小辅助函数的替代解决方案,以避免显式关闭文件.
use v6;
sub with-file($path, *&cb, *%adverbs) {
given open($path, |%adverbs) {
.&cb;
.close;
}
}
my $path = 'fileio.txt';
# Open $path for writing.
with-file $path, :w, {
.say('hello'); # Print the line "hello\n" to it.
};
# Open the file for appending.
with-file $path, :a, {
.say('world'); # Append the line "world\n" to it.
};
my $line = lines($path)[1]; # Get the second line. lines returns a lazy iterator.
say $line; # Perl 6 filehandles autochomp, so we use say to add a newline.
Run Code Online (Sandbox Code Playgroud)
% read_line_to_codes is defined in YAP library already.
% Uncomment the next line and remove the makeshift replacement definition to use it.
% use_module(library(readutil)).
readcodes(Stream,[]) :- peek_char(Stream,'\n'),get_char(Stream,'\n');peek_char(Stream,end_of_file).
readcodes(Stream,[First|Rest]) :- get_code(Stream,First),readcodes(Stream,Rest).
read_line_to_codes(Stream,Line) :- readcodes(Stream,Line),!.
:- open('fileio.txt',write,Stream),write(Stream,'hello\n'),close(Stream).
:- open('fileio.txt',append,Stream),write(Stream,'world'),close(Stream).
secondline(L) :- open('fileio.txt',read,Stream),read_line_to_codes(Stream,_),read_line_to_codes(Stream,L),close(Stream).
:- secondline(L),format('~s\n',[L]).
Run Code Online (Sandbox Code Playgroud)
小智 7
io.open( 'TestIO.txt', 'w' ):write( 'hello' ):write( '\n', 'world' ):close()
aLine = io.open( 'TestIO.txt', 'r' ):read( '*a' ):match( '%C*%c*(.*)' )
print( aLine )
Run Code Online (Sandbox Code Playgroud)
小智 7
set f [open fileio.txt w+]
puts $f hello
puts $f world
seek $f 0
puts [lindex [split [read $f] \n] 1]
close $f
Run Code Online (Sandbox Code Playgroud)
#!/bin/bash
echo 'hello' > fileio.txt
echo 'world' >> fileio.txt
myvar=`tail -n 1 fileio.txt`
echo $myvar
Run Code Online (Sandbox Code Playgroud)
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h> /* For error reporting */
#define BUFFER_SIZE 6
int main (int argc, char *argv[])
{
int fd;
const char HELLO[] = "hello\n";
const char WORLD[] = "world\n";
if ((fd = open ("fileio.txt", O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)) < 0) {
perror ("open");
return 1;
}
if (write (fd, HELLO, sizeof (HELLO)) < 0) {
perror ("write");
return 1;
}
if (write (fd, WORLD, sizeof (WORLD)) < 0) {
perror ("write(2)");
return 1;
}
/* Rewind file */
lseek (fd, 0, SEEK_SET);
/* Read whole file */
int bytes_read;
do {
char buffer[BUFFER_SIZE];
bytes_read = read (fd, buffer, BUFFER_SIZE);
write (0, buffer, bytes_read);
} while (bytes_read > 0);
if (close (fd) != 0) {
perror ("close");
return 1;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 7
IoFile with("fileio.txt") open write("hello\n") write("world\n") \
rewind readLines second println
Run Code Online (Sandbox Code Playgroud)
这是最短的解决方案吗?
我最近一直在讨厌FORTRAN,所以这里有:
PROGRAM FILEIO
C WRITES TWO LINES TO A TEXT FILE AND THEN RETRIEVES THE SECOND OF
C THEM
CHARACTER*5 STRIN
OPEN(UNIT=1, FILE='FILEIO.TXT')
WRITE(1,100) 'HELLO'
WRITE (1,100) 'WORLD'
CLOSE(1)
C
OPEN(UNIT=2, FILE='FILEIO.TXT')
READ(2,100) STRIN
READ(2,100) STRIN
WRITE(*,*) STRIN
100 FORMAT(A5)
STOP
END
Run Code Online (Sandbox Code Playgroud)
由ldigas编辑:另一方面我更喜欢它
(抱歉弄乱你的答案;我不想开始另一个Fortran帖子)
character(10) :: line
open(1,file='fileio.txt',status='replace')
write(1,'("hello"/"world")'); rewind(1);
read(1,'(/a)')line; write(*,'(a)')line
end
Run Code Online (Sandbox Code Playgroud)
(这是一个较新的Fortran变种......只有15-20岁左右;-)
例1:
with open('fileio.txt', 'a') as f:
f.write('hello')
f.write('\nworld')
with open('fileio.txt') as f:
s = f.readlines()[1]
print s
Run Code Online (Sandbox Code Playgroud)
示例2 - 没有上下文管理器:
f = open('fileio.txt', 'a')
f.write('hello')
f.write('\nworld')
f.close()
f = open('fileio.txt')
s = f.readlines()[1]
f.close()
print s
Run Code Online (Sandbox Code Playgroud)
Visual Basic 6.0
open "fileio.txt" for output as #1
write #1, "hello"
close #1
open "fileio.txt" for append as #1
write #1, "world"
close #1
open "fileio.txt" for input as #1
dim strn as string
input #1, strn
input #1, strn
msgbox(strn)
close #1
Run Code Online (Sandbox Code Playgroud)
由于与磁盘空间和内存使用相关的历史原因.1969年,MUMPS允许你将命令截断为一个(或有时两个)字符,这就是为什么Clayton的例子看起来如此"怪异"(尽管我可以很容易地阅读它).以下是有关此MUMPS计划的更多信息.
FileIo ; Define a "label" identifying this piece of code (not a function here).
; MUMPS has only process-specific variable scope, so stack local
; variables with the 'New' command.
New File, Line1, Line2
Set File="FILEIO.TXT"
; MUMPS has a concept of a "currently open" device, which "Read" and "Write"
; commands use. Identify a device with the Open command and switch to the
; device with the "Use" command. Get rid of the device with the "Close"
; command.
; Another funny thing here is the "postconditional expression," which in this
; case is "WNS". In this case we pass arguments to the Open command. The
; exact meaning is implementation-specific but if I had to guess, these
; arguments have to do with opening the file for writing, using a newline
; character as a delimiter, etc.
Open File:"WNS" Use File Write "hello" Close File
Open File:"WAS" Use File Write !,"world" Close File ; ! = new line
; Here the "Read" command executes twice on the file, reading two lines into
; the variables "Line1" and "Line2". The Read command is probably aware of the
; line-oriented nature of the file because of the "RS" postconditional.
Open File:"RS" Use File Read Line1,Line2 Close File Write Line2,!
Quit
Run Code Online (Sandbox Code Playgroud)
小智 6
import tango.text.Util, tango.io.Stdout, tango.io.device.File;
void main()
{
scope file = new File ("fileio.txt", File.ReadWriteCreate);
file.write ("hello\n");
file.write ("world\n");
auto line = splitLines (file.rewind.text())[1];
stdout(line).nl;
}
Run Code Online (Sandbox Code Playgroud)
简明版:
void main()
{
with (new File ("fileio.txt", File.ReadWriteCreate))
stdout (lineOf (put("hello\n").put("world\n").rewind.text(), 1)).nl;
}
Run Code Online (Sandbox Code Playgroud)
之前已经提供了一个很好的C#示例,但我觉得包括如何逐行进行文件I/O以及流也会有所帮助.
string path = @"fileio.txt";
//creating file and writing to it
using (StreamWriter writer = File.CreateText(path))
{
writer.WriteLine("Hello");
}
//appending to existing file
using (StreamWriter writer = File.AppendText(path))
{
writer.WriteLine("World");
}
//reading file
using(StreamReader reader = File.OpenText(path))
{
int lineNum = 0;
string line = null;
while ((line = reader.ReadLine()) != null)//read until eof
{
if (++lineNum == 2)
{
Console.WriteLine(line);
}
}
}
Run Code Online (Sandbox Code Playgroud)
use 5.012;
use warnings;
use autodie;
# 1 & 2 - create and write line to file
open my $new, '>', 'fileio.txt';
say {$new} 'hello';
close $new;
# 3 - open file to append line
open my $append, '>>', 'fileio.txt';
say {$append} 'world';
close $append;
# 4 - read in second line to input string
my $line = do {
open my $read, '<', 'fileio.txt';
<$read>; # equivalent to: readline $read
<$read>; # last value expression gets returned from do{}
};
print $line; # 5 - print input string!
Run Code Online (Sandbox Code Playgroud)
以上是open在Modern Perl 中使用的基本示例(即三个arg open,lexical filehandles,autodie和say/print最佳实践).
但是,实际上没有必要使用$new和$append词法变量(包含文件句柄)来污染命名空间.所以对于第1-3点,我可能会觉得更开心:
{
open my $fh, '>', 'fileio.txt';
say {$fh} 'hello';
}
{
open my $fh, '>>', 'fileio.txt';
say {$fh} 'world';
}
Run Code Online (Sandbox Code Playgroud)
要么:
use IO::File; # core module
IO::File->new( 'fileio.txt', 'w' )->print( "hello\n" );
IO::File->new( 'fileio.txt', 'a' )->print( "world\n" );
Run Code Online (Sandbox Code Playgroud)
更新:澄清:写完第一行后不需要重新打开文本文件
并且没有提及是否需要重新打开文件以读取第二行,因此它可以像这样完成:
my $line = do {
open my $fh, '+>', 'fileio.txt';
say {$fh} $_ for qw/hello world/; # or just: say {$fh} "hello\nworld" :)
seek $fh, 0, 0; # rewind to top of file
(<$fh>)[1]; # no need to be lazy with just 2 recs!
};
print $line;
Run Code Online (Sandbox Code Playgroud)
/ I3az /
Iof := File with("fileio.txt")
f open
f write("hello")
f close
f openForAppending
f write("\nworld")
f close
f openForReading
secondLine := f readLines at(1)
f close
write(secondLine)
Run Code Online (Sandbox Code Playgroud)
var fileName = "fileio.txt";
var ForReading = 1;
var ForAppending = 8;
var fso = new ActiveXObject("Scripting.FileSystemObject")
// Create a file and write to it
var file = fso.CreateTextFile(fileName, true /* overwrite if exists */);
file.WriteLine("hello");
file.Close();
// Append to the file
file = fso.OpenTextFile(fileName, ForAppending);
file.WriteLine("world");
file.Close();
// Read from the file
file = fso.OpenTextFile(fileName, ForReading);
file.SkipLine();
var str = file.ReadLine();
file.Close();
WScript.Echo(str);
Run Code Online (Sandbox Code Playgroud)
Program pascalIO;
Var FName, TFile : String[15];
UserFile: Text;
Begin
FName := 'fileio.txt';
Assign(UserFile, FName);
Rewrite(UserFile);
Writeln(UserFile,'hello');
Writeln(UserFile,'world');
Close(UserFile);
Assign(UserFile, FName);
Reset(UserFile);
Readln(UserFile,TFile);
Readln(UserFile,TFile);
Writeln( TFile);
Close(UserFile);
End.
Run Code Online (Sandbox Code Playgroud)
open('fileio.txt', 'w').write('hello\n')
open('fileio.txt', 'a').write('world\n')
with open('fileio.txt', 'r') as f:
print f.readline() and f.readline(),
Run Code Online (Sandbox Code Playgroud)
f =: 'fileio.txt'
('hello', LF) 1!:2 < f
('world', LF) 1!:3 < f
; 1 { < ;. _2 (1!:1 < f)
Run Code Online (Sandbox Code Playgroud)
最后一行读取文件(1!:1 < f),将其剪切为行(< ;. _2),获取第二个元素(1 {).然后;Monadic用于拆除元素.
| 归档时间: |
|
| 查看次数: |
82372 次 |
| 最近记录: |