Hướng dẫn how do you read a file and write into another file in python? - làm thế nào để bạn đọc một tệp và ghi vào một tệp khác trong python?

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Xem thảo luận

    Cải thiện bài viết

    Lưu bài viết

    ĐọcReading and Writing to text files in Python

    Bàn luận

    • Điều kiện tiên quyết: Đọc và ghi vào các tệp văn bản trong Python In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in python by default.
    • Python cung cấp các chức năng sẵn có để tạo, viết và đọc các tệp. Hai loại tệp có thể được xử lý trong Python, tệp văn bản thông thường và tệp nhị phân (được viết bằng ngôn ngữ nhị phân, 0S và 1S). In this type of file, there is no terminator for a line, and the data is stored after converting it into machine-understandable binary language.

    Tệp văn bản: Trong loại tệp này, mỗi dòng văn bản được chấm dứt với một ký tự đặc biệt có tên EOL (cuối dòng), là ký tự dòng mới (‘\ n,) trong Python theo mặc định..txt file in Python.

    Approach:

    Tệp nhị phân: Trong loại tệp này, không có bộ hủy nào cho một dòng và dữ liệu được lưu trữ sau khi chuyển đổi nó thành ngôn ngữ nhị phân có thể hiểu bằng máy.

    • Trong bài viết này, chúng tôi sẽ tìm hiểu cách đọc nội dung từ một tệp và viết nó vào một tệp khác. Ở đây chúng tôi đang hoạt động trên tệp .txt trong Python.
    • Có hai cách tiếp cận để làm như vậy:

    Sử dụng các vòng lặp để đọc và sao chép nội dung từ tệp này sang tệp khác.

    Hướng dẫn how do you read a file and write into another file in python? - làm thế nào để bạn đọc một tệp và ghi vào một tệp khác trong python?

    Sử dụng các phương thức tệp để đọc và sao chép nội dung từ tệp này sang tệp khác.

    Approach:

    • Tệp đầu vào:
    • Phương pháp 1: Sử dụng các vòng lặp
    • Mở tệp đầu vào trong chế độ đọc.

    Mở tệp đầu ra trong chế độ ghi.

    Python3

    with open("gfg input file.txt",

    file1=open("inventory.txt","r")
    file2=open("purchasing.txt","w")
    data=file1.readline()
    for line in file1:
    
        items=data.strip()
        item=items.split()
    
        qty=int(item[3])
        reorder=int(item[4])
    
        if qty<=reorder:
            file2.write(item[0]+"\t"+item[1]+"\n")
    
    
    file1.close()
    file2.close()
    
    0
    file1=open("inventory.txt","r")
    file2=open("purchasing.txt","w")
    data=file1.readline()
    for line in file1:
    
        items=data.strip()
        item=items.split()
    
        qty=int(item[3])
        reorder=int(item[4])
    
        if qty<=reorder:
            file2.write(item[0]+"\t"+item[1]+"\n")
    
    
    file1.close()
    file2.close()
    
    1
    file1=open("inventory.txt","r")
    file2=open("purchasing.txt","w")
    data=file1.readline()
    for line in file1:
    
        items=data.strip()
        item=items.split()
    
        qty=int(item[3])
        reorder=int(item[4])
    
        if qty<=reorder:
            file2.write(item[0]+"\t"+item[1]+"\n")
    
    
    file1.close()
    file2.close()
    
    2
    file1=open("inventory.txt","r")
    file2=open("purchasing.txt","w")
    data=file1.readline()
    for line in file1:
    
        items=data.strip()
        item=items.split()
    
        qty=int(item[3])
        reorder=int(item[4])
    
        if qty<=reorder:
            file2.write(item[0]+"\t"+item[1]+"\n")
    
    
    file1.close()
    file2.close()
    
    3

    file1=open("inventory.txt","r")
    file2=open("purchasing.txt","w")
    data=file1.readline()
    for line in file1:
    
        items=data.strip()
        item=items.split()
    
        qty=int(item[3])
        reorder=int(item[4])
    
        if qty<=reorder:
            file2.write(item[0]+"\t"+item[1]+"\n")
    
    
    file1.close()
    file2.close()
    
    4with open(
    file1=open("inventory.txt","r")
    file2=open("purchasing.txt","w")
    data=file1.readline()
    for line in file1:
    
        items=data.strip()
        item=items.split()
    
        qty=int(item[3])
        reorder=int(item[4])
    
        if qty<=reorder:
            file2.write(item[0]+"\t"+item[1]+"\n")
    
    
    file1.close()
    file2.close()
    
    8,
    # Modern way to open files. The closing in handled cleanly
    with open('inventory.txt', mode='r') as in_file, \
         open('purchasing.txt', mode='w') as out_file:
    
        # A file is iterable
        # We can read each line with a simple for loop
        for line in in_file:
    
            # Tuple unpacking is more Pythonic and readable
            # than using indices
            ref, name, price, quantity, reorder = line.split()
    
            # Turn strings into integers
            quantity, reorder = int(quantity), int(reorder)
    
            if quantity <= reorder:
                # Use f-strings (Python 3) instead of concatenation
                out_file.write(f'{ref}\t{name}\n')
    
    0
    # Modern way to open files. The closing in handled cleanly
    with open('inventory.txt', mode='r') as in_file, \
         open('purchasing.txt', mode='w') as out_file:
    
        # A file is iterable
        # We can read each line with a simple for loop
        for line in in_file:
    
            # Tuple unpacking is more Pythonic and readable
            # than using indices
            ref, name, price, quantity, reorder = line.split()
    
            # Turn strings into integers
            quantity, reorder = int(quantity), int(reorder)
    
            if quantity <= reorder:
                # Use f-strings (Python 3) instead of concatenation
                out_file.write(f'{ref}\t{name}\n')
    
    1

    Đọc các dòng từ tệp đầu vào và ghi nó vào tệp đầu ra.

    # Modern way to open files. The closing in handled cleanly
    with open('inventory.txt', mode='r') as in_file, \
         open('purchasing.txt', mode='w') as out_file:
    
        # A file is iterable
        # We can read each line with a simple for loop
        for line in in_file:
    
            # Tuple unpacking is more Pythonic and readable
            # than using indices
            ref, name, price, quantity, reorder = line.split()
    
            # Turn strings into integers
            quantity, reorder = int(quantity), int(reorder)
    
            if quantity <= reorder:
                # Use f-strings (Python 3) instead of concatenation
                out_file.write(f'{ref}\t{name}\n')
    
    8
    # Modern way to open files. The closing in handled cleanly
    with open('inventory.txt', mode='r') as in_file, \
         open('purchasing.txt', mode='w') as out_file:
    
        # A file is iterable
        # We can read each line with a simple for loop
        for line in in_file:
    
            # Tuple unpacking is more Pythonic and readable
            # than using indices
            ref, name, price, quantity, reorder = line.split()
    
            # Turn strings into integers
            quantity, reorder = int(quantity), int(reorder)
    
            if quantity <= reorder:
                # Use f-strings (Python 3) instead of concatenation
                out_file.write(f'{ref}\t{name}\n')
    
    9

    Output:

    Hướng dẫn how do you read a file and write into another file in python? - làm thế nào để bạn đọc một tệp và ghi vào một tệp khác trong python?

    Dưới đây là việc thực hiện phương pháp trên:

    Approach:

    • # Modern way to open files. The closing in handled cleanly
      with open('inventory.txt', mode='r') as in_file, \
           open('purchasing.txt', mode='w') as out_file:
      
          # A file is iterable
          # We can read each line with a simple for loop
          for line in in_file:
      
              # Tuple unpacking is more Pythonic and readable
              # than using indices
              ref, name, price, quantity, reorder = line.split()
      
              # Turn strings into integers
              quantity, reorder = int(quantity), int(reorder)
      
              if quantity <= reorder:
                  # Use f-strings (Python 3) instead of concatenation
                  out_file.write(f'{ref}\t{name}\n')
      
      2
      # Modern way to open files. The closing in handled cleanly
      with open('inventory.txt', mode='r') as in_file, \
           open('purchasing.txt', mode='w') as out_file:
      
          # A file is iterable
          # We can read each line with a simple for loop
          for line in in_file:
      
              # Tuple unpacking is more Pythonic and readable
              # than using indices
              ref, name, price, quantity, reorder = line.split()
      
              # Turn strings into integers
              quantity, reorder = int(quantity), int(reorder)
      
              if quantity <= reorder:
                  # Use f-strings (Python 3) instead of concatenation
                  out_file.write(f'{ref}\t{name}\n')
      
      3
      # Modern way to open files. The closing in handled cleanly
      with open('inventory.txt', mode='r') as in_file, \
           open('purchasing.txt', mode='w') as out_file:
      
          # A file is iterable
          # We can read each line with a simple for loop
          for line in in_file:
      
              # Tuple unpacking is more Pythonic and readable
              # than using indices
              ref, name, price, quantity, reorder = line.split()
      
              # Turn strings into integers
              quantity, reorder = int(quantity), int(reorder)
      
              if quantity <= reorder:
                  # Use f-strings (Python 3) instead of concatenation
                  out_file.write(f'{ref}\t{name}\n')
      
      4
      # Modern way to open files. The closing in handled cleanly
      with open('inventory.txt', mode='r') as in_file, \
           open('purchasing.txt', mode='w') as out_file:
      
          # A file is iterable
          # We can read each line with a simple for loop
          for line in in_file:
      
              # Tuple unpacking is more Pythonic and readable
              # than using indices
              ref, name, price, quantity, reorder = line.split()
      
              # Turn strings into integers
              quantity, reorder = int(quantity), int(reorder)
      
              if quantity <= reorder:
                  # Use f-strings (Python 3) instead of concatenation
                  out_file.write(f'{ref}\t{name}\n')
      
      5
      file1=open("inventory.txt","r")
      file2=open("purchasing.txt","w")
      data=file1.readline()
      for line in file1:
      
          items=data.strip()
          item=items.split()
      
          qty=int(item[3])
          reorder=int(item[4])
      
          if qty<=reorder:
              file2.write(item[0]+"\t"+item[1]+"\n")
      
      
      file1.close()
      file2.close()
      
      2
      file1=open("inventory.txt","r")
      file2=open("purchasing.txt","w")
      data=file1.readline()
      for line in file1:
      
          items=data.strip()
          item=items.split()
      
          qty=int(item[3])
          reorder=int(item[4])
      
          if qty<=reorder:
              file2.write(item[0]+"\t"+item[1]+"\n")
      
      
      file1.close()
      file2.close()
      
      3
    • Phương pháp 2: Sử dụng phương thức tệp
    • Tạo/mở một tệp đầu ra ở chế độ viết.
    • Mở tệp đầu vào ở chế độ đọc

    Mở tệp đầu ra trong chế độ ghi.

    Python3

    Đọc các dòng từ tệp đầu vào và ghi nó vào tệp đầu ra.

    with open("gfg input file.txt",

    file1=open("inventory.txt","r")
    file2=open("purchasing.txt","w")
    data=file1.readline()
    for line in file1:
    
        items=data.strip()
        item=items.split()
    
        qty=int(item[3])
        reorder=int(item[4])
    
        if qty<=reorder:
            file2.write(item[0]+"\t"+item[1]+"\n")
    
    
    file1.close()
    file2.close()
    
    0
    to-56   Olive
    to-65   Green
    
    4

    Dưới đây là việc thực hiện phương pháp trên:

    to-56   Olive
    to-65   Green
    
    7

    Output:

    Hướng dẫn how do you read a file and write into another file in python? - làm thế nào để bạn đọc một tệp và ghi vào một tệp khác trong python?


    Tôi có một tệp có nội dung như được đưa ra dưới đây,

    to-56  Olive  850.00  10 10
    to-78  Sauce  950.00  25 20
    to-65  Green  100.00   6 10
    

    Nếu cột thứ 4 của dữ liệu nhỏ hơn hoặc bằng cột thứ 5, dữ liệu sẽ được ghi vào tệp thứ hai. Tôi đã thử mã sau, nhưng chỉ 'TO-56 OLIVE' được lưu trong tệp thứ hai. Tôi không thể hiểu những gì tôi đang làm sai ở đây.
    I tried the following code, but only 'to-56 Olive' is saved in the second file. I can't figure out what I'm doing wrong here.

    file1=open("inventory.txt","r")
    file2=open("purchasing.txt","w")
    data=file1.readline()
    for line in file1:
    
        items=data.strip()
        item=items.split()
    
        qty=int(item[3])
        reorder=int(item[4])
    
        if qty<=reorder:
            file2.write(item[0]+"\t"+item[1]+"\n")
    
    
    file1.close()
    file2.close()
    

    sshashank124

    30.4K8 Huy hiệu vàng63 Huy hiệu bạc75 Huy hiệu Đồng8 gold badges63 silver badges75 bronze badges

    Đã hỏi ngày 20 tháng 5 năm 2018 lúc 13:24May 20, 2018 at 13:24

    Hướng dẫn how do you read a file and write into another file in python? - làm thế nào để bạn đọc một tệp và ghi vào một tệp khác trong python?

    Upeka Fernando Upeka FernandoUpeka Fernando

    751 huy hiệu vàng1 huy hiệu bạc6 huy hiệu đồng1 gold badge1 silver badge6 bronze badges

    5

    Bạn đang đọc chỉ một dòng đầu vào. Vì vậy, bạn có thể có nhiều nhất một dòng đầu ra.

    Tôi thấy rằng mã của bạn là một chút "trường học cũ". Đây là một phiên bản "hiện đại" và pythonic hơn.

    # Modern way to open files. The closing in handled cleanly
    with open('inventory.txt', mode='r') as in_file, \
         open('purchasing.txt', mode='w') as out_file:
    
        # A file is iterable
        # We can read each line with a simple for loop
        for line in in_file:
    
            # Tuple unpacking is more Pythonic and readable
            # than using indices
            ref, name, price, quantity, reorder = line.split()
    
            # Turn strings into integers
            quantity, reorder = int(quantity), int(reorder)
    
            if quantity <= reorder:
                # Use f-strings (Python 3) instead of concatenation
                out_file.write(f'{ref}\t{name}\n')
    

    Đã trả lời ngày 20 tháng 5 năm 2018 lúc 14:28May 20, 2018 at 14:28

    Hướng dẫn how do you read a file and write into another file in python? - làm thế nào để bạn đọc một tệp và ghi vào một tệp khác trong python?

    1

    Tôi đã thay đổi mã của bạn một bit nhỏ, tất cả những gì bạn cần làm là lặp lại các dòng trong tệp của bạn - như thế này:

    file1=open("inventory.txt","r")
    file2=open("purchasing.txt","w")
    
    # Iterate over each line in the file
    for line in file1.readlines():
    
        # Separate each item in the line
        items=line.split()
    
        # Retrieve important bits
        qty=int(items[3])
        reorder=int(items[4])
    
        # Write to the file if conditions are met
        if qty<=reorder:
            file2.write(items[0]+"\t"+items[1]+"\n")
    
    # Release used resources
    file1.close()
    file2.close()
    

    Đây là đầu ra trong Mua hàng.txt:

    to-56   Olive
    to-65   Green
    

    Đã trả lời ngày 20 tháng 5 năm 2018 lúc 13:48May 20, 2018 at 13:48

    Hướng dẫn how do you read a file and write into another file in python? - làm thế nào để bạn đọc một tệp và ghi vào một tệp khác trong python?

    KacperitokacperitoKacperito

    1.2679 huy hiệu bạc22 Huy hiệu đồng9 silver badges22 bronze badges

    3

    Làm cách nào để đọc một tệp và ghi nó vào một tệp khác?

    Trong bài viết này, chúng tôi sẽ tìm hiểu cách đọc nội dung từ một tệp và ghi nó vào một tệp khác ...
    Tạo/mở tệp đầu ra ở chế độ viết ..
    Mở tệp đầu vào ở chế độ đọc ..
    Đọc từng dòng từ tệp đầu vào và ghi nó vào tệp đầu ra ..
    Đóng tệp đầu ra ..

    Làm cách nào để chuyển dữ liệu từ tệp này sang tệp khác trong Python?

    Mã Python giải thích về việc sao chép tệp từ SRC đến đích..
    Bước 2: Đọc vị trí tệp đích và tên tệp.>>> Dest_File_Location = OS.....
    Bước 3: Đọc nội dung tệp nguồn (tùy chọn) ....
    Bước 4: Viết nội dung tệp nguồn vào tệp đích.....
    Bước 5: Đọc nội dung tệp đích (tùy chọn).

    Hoạt động tệp đọc và ghi trong Python là gì?

    Readlines (): Hàm này trả về một danh sách trong đó mỗi phần tử là một dòng của tệp đó.Readlines (): Hàm này trả về một danh sách trong đó mỗi phần tử là một dòng của tệp đó.Viết (): Hàm này ghi một chuỗi các ký tự cố định vào một tệp.WriteLines (): Hàm này viết một danh sách chuỗi.