Hướng dẫn how do you insert a file in python? - làm thế nào để bạn chèn một tệp trong python?

Có cách nào để làm việc này không? Giả sử tôi có một tệp đó là danh sách các tên diễn ra như thế này:

  1. Alfred
  2. Hóa đơn
  3. Donald

Làm thế nào tôi có thể chèn tên thứ ba, "Charlie", ở dòng X [trong trường hợp này là 3] và tự động gửi tất cả những người khác xuống một dòng? Tôi đã thấy những câu hỏi khác như thế này, nhưng họ không nhận được câu trả lời hữu ích. Nó có thể được thực hiện, tốt nhất là với một phương thức hoặc một vòng lặp?

Khi được hỏi ngày 8 tháng 5 năm 2012 lúc 22:04May 8, 2012 at 22:04

3

Đây là một cách để thực hiện các mẹo.

with open["path_to_file", "r"] as f:
    contents = f.readlines[]

contents.insert[index, value]

with open["path_to_file", "w"] as f:
    contents = "".join[contents]
    f.write[contents]

import os, fileinput

old = "A"
new = "B"

for line in fileinput.FileInput[file_path, inplace=True]:
    if old in line :
        line += new + os.linesep
    print[line, end=""]
1 và
import os, fileinput

old = "A"
new = "B"

for line in fileinput.FileInput[file_path, inplace=True]:
    if old in line :
        line += new + os.linesep
    print[line, end=""]
2 là dòng và giá trị bạn chọn, các dòng bắt đầu từ 0.

wjandrea

25.1k8 Huy hiệu vàng53 Huy hiệu bạc73 Huy hiệu đồng8 gold badges53 silver badges73 bronze badges

Đã trả lời ngày 8 tháng 5 năm 2012 lúc 22:10May 8, 2012 at 22:10

Martinchomartinchomartincho

4.3076 Huy hiệu vàng31 Huy hiệu bạc41 Huy hiệu Đồng6 gold badges31 silver badges41 bronze badges

4

Nếu bạn muốn tìm kiếm một tệp cho một chuỗi con và thêm một văn bản mới vào dòng tiếp theo, một trong những cách thanh lịch để làm điều đó là như sau:

import os, fileinput

old = "A"
new = "B"

for line in fileinput.FileInput[file_path, inplace=True]:
    if old in line :
        line += new + os.linesep
    print[line, end=""]

Andyhasit

13.3K7 Huy hiệu vàng46 Huy hiệu bạc 50 Huy hiệu Đồng7 gold badges46 silver badges50 bronze badges

Đã trả lời ngày 20 tháng 10 năm 2015 lúc 14:38Oct 20, 2015 at 14:38

DavidsdavidsDavidS

2.0521 Huy hiệu vàng18 Huy hiệu bạc21 Huy hiệu đồng1 gold badge18 silver badges21 bronze badges

4

Có sự kết hợp các kỹ thuật mà tôi thấy hữu ích trong việc giải quyết vấn đề này:

with open[file, 'r+'] as fd:
    contents = fd.readlines[]
    contents.insert[index, new_string]  # new_string should end in a newline
    fd.seek[0]  # readlines consumes the iterator, so we need to start over
    fd.writelines[contents]  # No need to truncate as we are increasing filesize

Trong ứng dụng cụ thể của chúng tôi, chúng tôi muốn thêm nó sau một chuỗi nhất định:

with open[file, 'r+'] as fd:
    contents = fd.readlines[]
    if match_string in contents[-1]:  # Handle last line to prevent IndexError
        contents.append[insert_string]
    else:
        for index, line in enumerate[contents]:
            if match_string in line and insert_string not in contents[index + 1]:
                contents.insert[index + 1, insert_string]
                break
    fd.seek[0]
    fd.writelines[contents]

Nếu bạn muốn nó chèn chuỗi sau mỗi phiên bản của trận đấu, thay vì chỉ là lần đầu tiên, hãy xóa

import os, fileinput

old = "A"
new = "B"

for line in fileinput.FileInput[file_path, inplace=True]:
    if old in line :
        line += new + os.linesep
    print[line, end=""]
3 [và không đồng nhất] và
import os, fileinput

old = "A"
new = "B"

for line in fileinput.FileInput[file_path, inplace=True]:
    if old in line :
        line += new + os.linesep
    print[line, end=""]
4.

Cũng lưu ý rằng

import os, fileinput

old = "A"
new = "B"

for line in fileinput.FileInput[file_path, inplace=True]:
    if old in line :
        line += new + os.linesep
    print[line, end=""]
5 ngăn không cho nó thêm nhiều bản sao sau
import os, fileinput

old = "A"
new = "B"

for line in fileinput.FileInput[file_path, inplace=True]:
    if old in line :
        line += new + os.linesep
    print[line, end=""]
6, do đó an toàn khi chạy nhiều lần.

Đã trả lời ngày 2 tháng 6 năm 2017 lúc 22:55Jun 2, 2017 at 22:55

TemporalwolftemporalwolfTemporalWolf

7.3921 Huy hiệu vàng31 Huy hiệu bạc46 Huy hiệu đồng1 gold badge31 silver badges46 bronze badges

3

Bạn chỉ có thể đọc dữ liệu vào một danh sách và chèn bản ghi mới nơi bạn muốn.

names = []
with open['names.txt', 'r+'] as fd:
    for line in fd:
        names.append[line.split[' '][-1].strip[]]

    names.insert[2, "Charlie"] # element 2 will be 3. in your list
    fd.seek[0]
    fd.truncate[]

    for i in xrange[len[names]]:
        fd.write["%d. %s\n" %[i + 1, names[i]]]

Đã trả lời ngày 8 tháng 5 năm 2012 lúc 22:13May 8, 2012 at 22:13

Jordanmjordanmjordanm

Phù bằng vàng 31K7 Huy hiệu bạc72 Huy hiệu đồng7 gold badges60 silver badges72 bronze badges

0

Câu trả lời được chấp nhận phải tải toàn bộ tệp vào bộ nhớ, không hoạt động độc đáo cho các tệp lớn. Giải pháp sau đây ghi nội dung tệp với dữ liệu mới được chèn vào dòng bên phải vào một tệp tạm thời trong cùng một thư mục [do đó trên cùng một hệ thống tệp], chỉ đọc các đoạn nhỏ từ tệp nguồn tại một thời điểm. Sau đó, nó ghi đè lên tệp nguồn với nội dung của tệp tạm thời theo cách hiệu quả [Python 3.8+].

from pathlib import Path
from shutil import copyfile
from tempfile import NamedTemporaryFile

sourcefile = Path["/path/to/source"].resolve[]
insert_lineno = 152  # The line to insert the new data into.
insert_data = "..."  # Some string to insert.

with sourcefile.open[mode="r"] as source:
    destination = NamedTemporaryFile[mode="w", dir=str[sourcefile.parent]]
    lineno = 1

    while lineno < insert_lineno:
        destination.file.write[source.readline[]]
        lineno += 1

    # Insert the new data.
    destination.file.write[insert_data]

    # Write the rest in chunks.
    while True:
        data = source.read[1024]
        if not data:
            break
        destination.file.write[data]

# Finish writing data.
destination.flush[]
# Overwrite the original file's contents with that of the temporary file.
# This uses a memory-optimised copy operation starting from Python 3.8.
copyfile[destination.name, str[sourcefile]]
# Delete the temporary file.
destination.close[]

Chỉnh sửa 2020-09-08: Tôi vừa tìm thấy câu trả lời về đánh giá mã thực hiện một cái gì đó tương tự như ở trên với nhiều lời giải thích hơn-nó có thể hữu ích cho một số người.

Đã trả lời ngày 13 tháng 6 năm 2020 lúc 22:13Jun 13, 2020 at 22:13

SeanseanSean

1.28613 Huy hiệu bạc24 Huy hiệu đồng13 silver badges24 bronze badges

Bạn không cho chúng tôi thấy đầu ra sẽ trông như thế nào, vì vậy một cách giải thích có thể là bạn muốn đây là đầu ra:

  1. Alfred
  2. Hóa đơn
  3. Charlie
  4. Donald

[Chèn Charlie, sau đó thêm 1 vào tất cả các dòng tiếp theo.] Đây là một giải pháp khả thi:

def insert_line[input_stream, pos, new_name, output_stream]:
  inserted = False
  for line in input_stream:
    number, name = parse_line[line]
    if number == pos:
      print >> output_stream, format_line[number, new_name]
      inserted = True
    print >> output_stream, format_line[number if not inserted else [number + 1], name]

def parse_line[line]:
  number_str, name = line.strip[].split[]
  return [get_number[number_str], name]

def get_number[number_str]:
  return int[number_str.split['.'][0]]

def format_line[number, name]:
  return add_dot[number] + ' ' + name

def add_dot[number]:
  return str[number] + '.'

input_stream = open['input.txt', 'r']
output_stream = open['output.txt', 'w']

insert_line[input_stream, 3, 'Charlie', output_stream]

input_stream.close[]
output_stream.close[]

Đã trả lời ngày 9 tháng 5 năm 2012 lúc 1:27May 9, 2012 at 1:27

redcurryredcurryredcurry

2.2112 Huy hiệu vàng23 Huy hiệu bạc35 Huy hiệu Đồng2 gold badges23 silver badges35 bronze badges

  1. Phân tích tập tin vào danh sách Python bằng cách sử dụng
    import os, fileinput
    
    old = "A"
    new = "B"
    
    for line in fileinput.FileInput[file_path, inplace=True]:
        if old in line :
            line += new + os.linesep
        print[line, end=""]
    
    7 hoặc
    import os, fileinput
    
    old = "A"
    new = "B"
    
    for line in fileinput.FileInput[file_path, inplace=True]:
        if old in line :
            line += new + os.linesep
        print[line, end=""]
    
    8
  2. Xác định vị trí mà bạn phải chèn một dòng mới, theo tiêu chí của bạn.
  3. Chèn một phần tử danh sách mới ở đó bằng cách sử dụng
    import os, fileinput
    
    old = "A"
    new = "B"
    
    for line in fileinput.FileInput[file_path, inplace=True]:
        if old in line :
            line += new + os.linesep
        print[line, end=""]
    
    9.
  4. Viết kết quả vào tệp.

Đã trả lời ngày 8 tháng 5 năm 2012 lúc 22:10May 8, 2012 at 22:10

MartinchomartinchoAbhranil Das

4.3076 Huy hiệu vàng31 Huy hiệu bạc41 Huy hiệu Đồng6 gold badges34 silver badges42 bronze badges

1

location_of_line = 0
with open[filename, 'r'] as file_you_want_to_read:
     #readlines in file and put in a list
     contents = file_you_want_to_read.readlines[]

     #find location of what line you want to insert after
     for index, line in enumerate[contents]:
            if line.startswith['whatever you are looking for']
                   location_of_line = index

#now you have a list of every line in that file
context.insert[location_of_line, "whatever you want to append to middle of file"]
with open[filename, 'w'] as file_to_write_to:
        file_to_write_to.writelines[contents]

Nếu bạn muốn tìm kiếm một tệp cho một chuỗi con và thêm một văn bản mới vào dòng tiếp theo, một trong những cách thanh lịch để làm điều đó là như sau:

Andyhasit

13.3K7 Huy hiệu vàng46 Huy hiệu bạc 50 Huy hiệu Đồng

Đã trả lời ngày 20 tháng 10 năm 2015 lúc 14:38

DavidsdavidsOct 21, 2019 at 5:55

2.0521 Huy hiệu vàng18 Huy hiệu bạc21 Huy hiệu đồng

line_index = 3
lines = None
with open['file.txt', 'r'] as file_handler:
    lines = file_handler.readlines[]

lines.insert[line_index, 'Charlie']

with open['file.txt', 'w'] as file_handler:
    file_handler.writelines[lines]

Có sự kết hợp các kỹ thuật mà tôi thấy hữu ích trong việc giải quyết vấn đề này:Feb 5, 2019 at 12:55

Trong ứng dụng cụ thể của chúng tôi, chúng tôi muốn thêm nó sau một chuỗi nhất định:amrezzd

Nếu bạn muốn nó chèn chuỗi sau mỗi phiên bản của trận đấu, thay vì chỉ là lần đầu tiên, hãy xóa

import os, fileinput

old = "A"
new = "B"

for line in fileinput.FileInput[file_path, inplace=True]:
    if old in line :
        line += new + os.linesep
    print[line, end=""]
3 [và không đồng nhất] và
import os, fileinput

old = "A"
new = "B"

for line in fileinput.FileInput[file_path, inplace=True]:
    if old in line :
        line += new + os.linesep
    print[line, end=""]
4.14 silver badges35 bronze badges

Cũng lưu ý rằng

import os, fileinput

old = "A"
new = "B"

for line in fileinput.FileInput[file_path, inplace=True]:
    if old in line :
        line += new + os.linesep
    print[line, end=""]
5 ngăn không cho nó thêm nhiều bản sao sau
import os, fileinput

old = "A"
new = "B"

for line in fileinput.FileInput[file_path, inplace=True]:
    if old in line :
        line += new + os.linesep
    print[line, end=""]
6, do đó an toàn khi chạy nhiều lần.

Đã trả lời ngày 2 tháng 6 năm 2017 lúc 22:55 This code loads all the file into ram and rewrites content to the file

Temporalwolftemporalwolfstring and end with '\n' if you don't want it to mess with existing data.

with open["path_to_file", "r+"] as f:
    # Read the content into a variable
    contents = f.readlines[]
    contents.insert[index, value]
    
    # Reset the reader's location [in bytes]
    f.seek[0]
    
    # Rewrite the content to the file
    f.writelines[contents]

7.3921 Huy hiệu vàng31 Huy hiệu bạc46 Huy hiệu đồng

Bạn chỉ có thể đọc dữ liệu vào một danh sách và chèn bản ghi mới nơi bạn muốn.Mar 16 at 18:14

Đã trả lời ngày 8 tháng 5 năm 2012 lúc 22:13KlinZ

Jordanmjordanm4 bronze badges

Phù bằng vàng 31K7 Huy hiệu bạc72 Huy hiệu đồng

Bạn có thể để lại một bộ đệm của các ký tự null vô hình ['\ 0'] tại vị trí chèn để ghi đè sau:

import os, fileinput

old = "A"
new = "B"

for line in fileinput.FileInput[file_path, inplace=True]:
    if old in line :
        line += new + os.linesep
    print[line, end=""]
0

Thật không may, không có cách nào để xóa-without-retplation bất kỳ ký tự null dư thừa nào không bị ghi đè [hoặc nói chung bất kỳ ký tự nào ở giữa một tệp], trừ khi bạn viết lại mọi thứ sau đó. Nhưng các ký tự null sẽ không ảnh hưởng đến cách tệp của bạn trông với con người [chúng có chiều rộng bằng không].

Đã trả lời ngày 16 tháng 7 năm 2019 lúc 18:26Jul 16, 2019 at 18:26

1

Làm cách nào để thêm một tệp trong Python?

Với việc ghi vào tệp Python, bạn có thể tạo một tệp .text [Guru99.txt] bằng cách sử dụng mã, chúng tôi đã trình diễn ở đây:..
Bước 1] Mở tệp .txt f = Mở ["Guru99.txt", "W+"] ....
Bước 2] Nhập dữ liệu vào tệp cho I trong phạm vi [10]: f.write ["Đây là dòng % d \ r \ n" % [i+1]] ....
Bước 3] Đóng phiên bản tệp f.close [].

Làm thế nào để bạn nhập một tệp văn bản vào Python?

Để đọc một tệp văn bản trong Python, bạn làm theo các bước sau: Đầu tiên, hãy mở một tệp văn bản để đọc bằng cách sử dụng hàm Open [].Thứ hai, đọc văn bản từ tệp văn bản bằng cách sử dụng phương thức read [], readline [] hoặc readlines [] của đối tượng tệp.Thứ ba, đóng tệp bằng phương thức đóng tệp [].

Làm thế nào để bạn nối và đọc một tập tin trong Python?

Có 6 chế độ truy cập trong Python ...
Chỉ đọc ['r']: Mở tệp văn bản để đọc.....
Đọc và viết ['R+']: Mở tệp để đọc và viết.....
Chỉ viết ['W']: Mở tệp để viết.....
Viết và đọc ['W+']: Mở tệp để đọc và viết.....
Chỉ nối thêm ['A']: Mở tệp để viết ..

Bài Viết Liên Quan

Chủ Đề