简体   繁体   English

如何使用 Racket 语言在纯文本文件的特定行写入字符串?

[英]How to write a string at a specific line of a plain text file using Racket language?

I am a newcomer in Racket language and I do not know how to write a string (a new line) at a specific line of a plain text file.我是 Racket 语言的新手,我不知道如何在纯文本文件的特定行写入字符串(新行)。

I have seen that the append procedure do the work inserting new lines at the end of the file.我已经看到append过程完成在文件末尾插入新行的工作。

Also, Racket documentation talks about Counting Positions, Lines, and Columns , however I found no easy understandable examples (at least to me).此外,Racket 文档讨论了Counting Positions, Lines, and Columns ,但是我发现没有容易理解的例子(至少对我而言)。

An example may illustrate better what I want.一个例子可以更好地说明我想要什么。

Suppose a file (called test.txt ) has 10 lines and I have to write a string " New information starts here."假设一个文件(称为test.txt )有 10 行,我必须写一个字符串" New information starts here." between line 7 and 8.在第 7 行和第 8 行之间。

I mean after the new line has been inserted successfully, the test.txt file is going to have 11 lines.我的意思是在成功插入新行后, test.txt文件将有 11 行。

Any help I will appreciate.任何帮助我将不胜感激。 Best.最好的事物。

The simplest is to make a copy of the old file and insert the new line while copying.最简单的就是复制旧文件,复制时插入新行。 Then delete the old file and rename the new file to have the old file name.然后删除旧文件并将新文件重命名为旧文件名。

The copying could be done as follows:可以按如下方式进行复制:

#lang racket

; insert-line : string number ->
;   Almost copies line for line the current input port to the current output port.
;   When line-number lines have been copied an extra line is inserted.
(define (insert-line line line-number)
  (for ([l (in-lines)]
        [i (in-naturals)])
    (when (= i line-number)
      (displayln line))
    (displayln l)))

; insert-line-in-file : file file string number ->
;   copies file-in to file-out and inserts the line line at the given line number.
(define (insert-line-in-file file-in file-out line line-number)
  (with-outout-to-file file-out
    (λ ()
      (with-input-from-file file-in
        (λ ()
          (insert-line line line-number))))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM