GVKun编程网logo

如何在Python中写入文件中的特定行?(如何在python中写入文件中的特定行数)

23

如果您想了解如何在Python中写入文件中的特定行?的相关知识,那么本文是一篇不可错过的文章,我们将对如何在python中写入文件中的特定行数进行全面详尽的解释,并且为您提供关于perl–如何在Uni

如果您想了解如何在Python中写入文件中的特定行?的相关知识,那么本文是一篇不可错过的文章,我们将对如何在python中写入文件中的特定行数进行全面详尽的解释,并且为您提供关于perl – 如何在Unix中打印文件中的特定行?、Python - 不会写入 csv 文件中的特定列,而是重新写入整行、Python-如何跳至巨大文本文件中的特定行?、python如何写入现有txt文件中的特定行的有价值的信息。

本文目录一览:

如何在Python中写入文件中的特定行?(如何在python中写入文件中的特定行数)

如何在Python中写入文件中的特定行?(如何在python中写入文件中的特定行数)

我有一个文件作为格式:

xxxxxyyyyyzzzzzttttt

我需要在xxxxx和yyyyy行之间写入文件,如下所示:

xxxxxmy_lineyyyyyyzzzzzttttt

答案1

小编典典
with open(''input'') as fin, open(''output'',''w'') as fout:    for line in fin:        fout.write(line)        if line == ''xxxxx\n'':           next_line = next(fin)           if next_line == ''yyyyy\n'':              fout.write(''my_line\n'')           fout.write(next_line)

这将插入之间的线路 发生xxxxx\nyyyyy\n在文件中。

另一种方法是编写一个函数以产生行,直到看到一个 xxxxx\nyyyyy\n

 def getlines(fobj,line1,line2):     for line in iter(fobj.readline,''''):  #This is necessary to get `fobj.tell` to work         yield line         if line == line1:             pos = fobj.tell()             next_line = next(fobj):             fobj.seek(pos)             if next_line == line2:                 return

然后,您可以使用此方法直接传递给writelines

with open(''input'') as fin, open(''output'',''w'') as fout:    fout.writelines(getlines(fin,''xxxxx\n'',''yyyyy\n''))    fout.write(''my_line\n'')    fout.writelines(fin)

perl – 如何在Unix中打印文件中的特定行?

perl – 如何在Unix中打印文件中的特定行?

我想从Unix中的文本文件中打印某些行.要打印的行号列在另一个文本文件中(每行一个).

有没有使用Perl或shell脚本快速完成此操作的方法?

解决方法

假设要打印的行号已排序.

open my $fh,'<','line_numbers' or die $!;
my @ln = <$fh>;
open my $tx,'text_file' or die $!;
foreach my $ln (@ln) {
  my $line;
  do {
    $line = <$tx>;
  } until $. == $ln and defined $line;
  print $line if defined $line;
}

Python - 不会写入 csv 文件中的特定列,而是重新写入整行

Python - 不会写入 csv 文件中的特定列,而是重新写入整行

如何解决Python - 不会写入 csv 文件中的特定列,而是重新写入整行?

以下代码用于确保员工可以从当天开始登录和打卡。当我尝试为员工打卡并输入所有小时数时,代码将其保存到文件中,但不在我想要的特定列中。它将通过替换整行并从头开始重写来保存它。但是,我希望它从第 7 列开始保存。

role = input("Choose role [E]mployee / [P]ayroll clerk [Default]:")

if role == "E" or role == "e":
    
    logged_in = False
    
file = open("user_pass.csv",''r'')

    user_pass_list = []

    for row in file:
        field = row.split(",")

        user_name = field[0]
        pass_word = field[1]
        user_id = field[2]
        user_pass_list.append([user_name,pass_word,user_id])
    file.close()
    while not logged_in:
        print("Please enter your details to log in:\n")
        user_name1 = input("Please enter your username: ")
        pass_word1 = input("Please enter your password: ")
        for item_num in range(0,len(user_pass_list)):
            if user_name1 == user_pass_list[item_num][0]:
                if pass_word1 == user_pass_list[item_num][1]:
                    logged_in = True
                    user_name = user_pass_list[item_num][0]
                    pass_word = user_pass_list[item_num][1]
                    user_id = user_pass_list[item_num][2]
        if not logged_in:
            print("Incorrect. Please try again.\n")

    print("Hello",user_name)

    clock = input("Clock [I]n / Clock [O]ut:")

    if clock == "I" or clock == "i":
        editfile = open("CafeTestData.csv","r")
        completion = "false"
        newfile = editfile.readlines()
        for line in newfile:
            if line.split(",")[0] == user_id:
                while completion == "false":
                    print(line)
                    details = line.split(",")

                    mon_time = input("Please enter the hours worked on Monday: ")

                    if mon_time == "":
                        mon_time = details[7]

                    tue_time = input("Please enter the hours worked on Tuesday: ")

                    if tue_time == "":
                        tue_time = details[8]

                    wed_time = input("Please enter the hours worked on Wednesday: ")

                    if wed_time == "":
                        wed_time = details[9]

                    thu_time = input("Please enter the hours worked on Thursday: ")

                    if thu_time == "":
                        thu_time = details[10]

                    fri_time = input("Please enter the hours worked on Friday: ")

                    if fri_time == "":
                        fri_time = details[11]

                    sat_time = input("Please enter the hours worked on Saturday: ")

                    if sat_time == "":
                        sat_time = details[12]

                    sun_time = input("Please enter the hours worked on Sunder: ")

                    if sun_time == "":
                        sun_time = details[13]

                    print(
                        mon_time + " " + tue_time + " " + wed_time + " " + thu_time + " " + fri_time + " " + sat_time + " " + sun_time)

                    confirmation = input("Are you sure this data is correct? [Y] or [No]: ")
                    if confirmation == "Y" or confirmation == "y":
                        newline = mon_time + "," + tue_time + "," + wed_time + "," + thu_time + "," + fri_time + "," + sat_time + "," + sun_time + "\n"
                        newfile.remove(line)
                        newfile.append(newline)
                        completion = True
                        editfile.close()
                        editfile = open("CafeTestData.csv","w")
                        editfile.writelines(newfile)
                        editfile.close()

                    if confirmation == "N" or confirmation == "n":
                        completion = False

解决方法

我主要使用 Pandas 库,我绝对向你推荐它,你可能想尝试 a 而不是 w,这是一个要附加的特殊字符:

open("CafeTestData.csv","a").write(text)

Python-如何跳至巨大文本文件中的特定行?

Python-如何跳至巨大文本文件中的特定行?

以下代码是否有替代方法:

startFromLine = 141978 # or whatever line I need to jump tourlsfile = open(filename, "rb", 0)linesCounter = 1for line in urlsfile:    if linesCounter > startFromLine:        DoSomethingWithThisLine(line)    linesCounter += 1

如果我正在处理一个巨大的文本文件(~15MB),其行数未知但长度不同,并且需要跳转到特定行我应该事先知道哪个号码?当我知道我至少可以忽略文件的前半部分时,我很难一一处理它们。寻找更优雅的解决方案(如果有)。

答案1

小编典典

由于你不知道换行符在哪里,因此无法至少一次不读入文件就无法跳转。你可以执行以下操作:

# Read in the file once and build a list of line offsetsline_offset = []offset = 0for line in file:    line_offset.append(offset)    offset += len(line)file.seek(0)# Now, to skip to line n (with the first line being line 0), just dofile.seek(line_offset[n])

python如何写入现有txt文件中的特定行

python如何写入现有txt文件中的特定行

我正在编写一个脚本,该脚本读取输入文件,获取值并需要在输出模板的特定位置(行)写入,我绝对是菜鸟,无法做到。它要么写在输出的第一行,要么写在最后一行。

打开的文件为“ r +”

使用的file.write(xyz)命令

关于如何向python解释以写入特定行的说法,例如。第17行(输出模板中的空白行)

编辑:

with open (MCNP_input,'r+') as M:
           line_to_replace = 17
           lines = M.readlines()
           if len(lines) > int (line_to_replace):
               lines[line_to_replace] = shape_sphere + radius + '\n'
               M.writelines(lines)

关于如何在Python中写入文件中的特定行?如何在python中写入文件中的特定行数的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于perl – 如何在Unix中打印文件中的特定行?、Python - 不会写入 csv 文件中的特定列,而是重新写入整行、Python-如何跳至巨大文本文件中的特定行?、python如何写入现有txt文件中的特定行等相关内容,可以在本站寻找。

本文标签: