Hướng dẫn how do i convert a number to a text file in python? - làm cách nào để chuyển đổi một số thành tệp văn bản trong python?

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

Lưu bài viết

Python Too hỗ trợ xử lý tệp và cho phép người dùng xử lý các tệp, tức là đọc và ghi các tệp, cùng với nhiều tùy chọn xử lý tệp khác, để hoạt động trên các tệp. Xử lý tệp dữ liệu trong Python được thực hiện trong hai loại tệp: & nbsp; & nbsp;
 

  • Tệp văn bản (tiện ích mở rộng .txt) & nbsp; & nbsp;
     
  • Tệp nhị phân (tiện ích mở rộng .Bin) & nbsp; & nbsp;
     

Ở đây chúng tôi đang hoạt động trên tệp .txt trong Python. Thông qua chương trình này, chúng tôi có thể trích xuất các số từ nội dung trong tệp văn bản và thêm tất cả và in kết quả. & NBSP;
 

Cách tiếp cận

Đọc nội dung của tệp, chúng tôi sẽ khớp loại ký tự với int. Nếu kết quả của sự bình đẳng là đúng, thì số sẽ được thêm vào số được lưu trữ trong bộ nhớ được phân bổ cho biến ‘A. Chúng tôi bắt đầu biến ’a ở đây với giá trị 0. & nbsp;
 

Python3

temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
2
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
3
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
4
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
5
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
6
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
7
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
8__

f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()
0
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
3
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()
2

temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
2
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()
4

temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
2
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()
6

Sử dụng mã trên, chúng tôi đã mở một tệp mới có tên ‘GFG, ở chế độ ghi. Sử dụng, hàm write () Chúng tôi đã chèn dữ liệu được phân bổ vào dữ liệu biến trong bộ nhớ. Sau đó, chúng tôi đã đóng tệp. Đọc từ tệp được tạo ở trên và trích xuất các số nguyên. & NBSP;write mode. Using, the write() function we inserted the data allocated to the variable data in the memory. After this, we closed the file.
Reading from the above-created file and extracting the integers.
 

Python3

f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()
7
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
3
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
4
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
5
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
6
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
7
with open('temps.txt') as f:
    for line in f.readlines():
        temps.append(float(line))
3
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
9

with open('temps.txt') as f:
    for line in f.readlines():
        temps.append(float(line))
5
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
3
with open('temps.txt') as f:
    for line in f.readlines():
        temps.append(float(line))
7

with open('temps.txt') as f:
    for line in f.readlines():
        temps.append(float(line))
8
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
3
import random

f = open('temps.txt','w')

for n in range(0,50):
    f.write('{:2.1f}\n'.format(random.random()*100))

f.close()
0

import random

f = open('temps.txt','w')

for n in range(0,50):
    f.write('{:2.1f}\n'.format(random.random()*100))

f.close()
1
import random

f = open('temps.txt','w')

for n in range(0,50):
    f.write('{:2.1f}\n'.format(random.random()*100))

f.close()
2
import random

f = open('temps.txt','w')

for n in range(0,50):
    f.write('{:2.1f}\n'.format(random.random()*100))

f.close()
3
import random

f = open('temps.txt','w')

for n in range(0,50):
    f.write('{:2.1f}\n'.format(random.random()*100))

f.close()
4

import random

f = open('temps.txt','w')

for n in range(0,50):
    f.write('{:2.1f}\n'.format(random.random()*100))

f.close()
5
import random

f = open('temps.txt','w')

for n in range(0,50):
    f.write('{:2.1f}\n'.format(random.random()*100))

f.close()
1
import random

f = open('temps.txt','w')

for n in range(0,50):
    f.write('{:2.1f}\n'.format(random.random()*100))

f.close()
7
import random

f = open('temps.txt','w')

for n in range(0,50):
    f.write('{:2.1f}\n'.format(random.random()*100))

f.close()
3
import random

f = open('temps.txt','w')

for n in range(0,50):
    f.write('{:2.1f}\n'.format(random.random()*100))

f.close()
9

def readData(fileName):
  """Generic data reading function:
     reads lines in a text file and
     splits them into lists."""
    data = []
    with open(fileName) as f:
        for line in f.readlines():
            data.append(lineToData(line.split()))
    return data
0
def readData(fileName):
  """Generic data reading function:
     reads lines in a text file and
     splits them into lists."""
    data = []
    with open(fileName) as f:
        for line in f.readlines():
            data.append(lineToData(line.split()))
    return data
1
def readData(fileName):
  """Generic data reading function:
     reads lines in a text file and
     splits them into lists."""
    data = []
    with open(fileName) as f:
        for line in f.readlines():
            data.append(lineToData(line.split()))
    return data
2
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
3
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
3
def readData(fileName):
  """Generic data reading function:
     reads lines in a text file and
     splits them into lists."""
    data = []
    with open(fileName) as f:
        for line in f.readlines():
            data.append(lineToData(line.split()))
    return data
5
def readData(fileName):
  """Generic data reading function:
     reads lines in a text file and
     splits them into lists."""
    data = []
    with open(fileName) as f:
        for line in f.readlines():
            data.append(lineToData(line.split()))
    return data
6

def readData(fileName):
  """Generic data reading function:
     reads lines in a text file and
     splits them into lists."""
    data = []
    with open(fileName) as f:
        for line in f.readlines():
            data.append(lineToData(line.split()))
    return data
7
with open('temps.txt') as f:
    for line in f.readlines():
        temps.append(float(line))
8
def readData(fileName):
  """Generic data reading function:
     reads lines in a text file and
     splits them into lists."""
    data = []
    with open(fileName) as f:
        for line in f.readlines():
            data.append(lineToData(line.split()))
    return data
9
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
3
1935  32.1
1940  30.5
1945  24.4
1950  23
1955  19.1
1960  15.6
1965  12.4
1970  9.7
1975  8.9
1980  7.2
1
1935  32.1
1940  30.5
1945  24.4
1950  23
1955  19.1
1960  15.6
1965  12.4
1970  9.7
1975  8.9
1980  7.2
2

1935  32.1
1940  30.5
1945  24.4
1950  23
1955  19.1
1960  15.6
1965  12.4
1970  9.7
1975  8.9
1980  7.2
3
temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
5
1935  32.1
1940  30.5
1945  24.4
1950  23
1955  19.1
1960  15.6
1965  12.4
1970  9.7
1975  8.9
1980  7.2
5
1935  32.1
1940  30.5
1945  24.4
1950  23
1955  19.1
1960  15.6
1965  12.4
1970  9.7
1975  8.9
1980  7.2
6

Output: 
 

The sum is: 24

Chương trình trên nhấn mạnh vào việc trích xuất các số từ nội dung được lưu trữ trong tệp văn bản có tên ‘GFG. Hơn nữa, các số sau đó được thêm vào sau khi đánh máy và được lưu trữ trong biến ‘A. & NBSP;
 


Đọc dữ liệu từ một tệp

Chương trình ví dụ dưới đây cho thấy những điều cơ bản của việc làm việc với dữ liệu đến từ một tệp văn bản. Chương trình được thiết kế để hoạt động với một tệp văn bản chứa các bài đọc nhiệt độ danh sách. Các bài đọc được liệt kê một trên mỗi dòng trong tệp văn bản. Chương trình sẽ đọc danh sách các bài đọc từ tệp văn bản, đặt các bài đọc vào danh sách, sau đó xác định và in các bài đọc nhiệt độ thấp nhất và cao nhất được tìm thấy trong tệp.

temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))

Dưới đây là một số điều cần lưu ý trong chương trình.

  1. Bước đầu tiên làm việc với một tệp là mở tệp. Hàm
    1935  32.1
    1940  30.5
    1945  24.4
    1950  23
    1955  19.1
    1960  15.6
    1965  12.4
    1970  9.7
    1975  8.9
    1980  7.2
    
    7 mở một tệp để đọc và trả về một đối tượng tệp. Tham số đến
    1935  32.1
    1940  30.5
    1945  24.4
    1950  23
    1955  19.1
    1960  15.6
    1965  12.4
    1970  9.7
    1975  8.9
    1980  7.2
    
    7 chỉ định tên của tệp để mở.
  2. 1935  32.1
    1940  30.5
    1945  24.4
    1950  23
    1955  19.1
    1960  15.6
    1965  12.4
    1970  9.7
    1975  8.9
    1980  7.2
    
    9 Trả về một danh sách các dòng trong tệp văn bản. Chúng tôi thiết lập một vòng lặp để lặp lại danh sách các dòng này.
  3. Mỗi dòng trong tệp văn bản là một chuỗi. Chúng ta phải chuyển đổi chuỗi đó thành một chiếc phao trước khi nối nó vào danh sách các temps.
  4. Khi chúng tôi đọc xong dữ liệu từ tệp, chúng tôi sử dụng phương thức
    ["1935","32.1"]
    
    0 để đóng tệp.

Vì chúng tôi luôn phải cẩn thận để đóng một tệp sau khi chúng tôi hoàn thành làm việc với nó, nên có thể hữu ích khi sử dụng một công trình thay thế để quản lý mở và đóng tệp. Cấu trúc Python

["1935","32.1"]
1 rất hữu ích cho mục đích này.

Thay cho

f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

chúng tôi có thể làm

with open('temps.txt') as f:
    for line in f.readlines():
        temps.append(float(line))

Khi chúng ta thoát khỏi phần thân của cấu trúc, tệp sẽ tự động đóng cho chúng tôi. Ngoài ra, nếu chương trình tạo ra một lỗi ở bất cứ đâu trong cơ thể, chương trình sẽ tự động thoát khỏi phần thân của và đóng tệp cho chúng tôi.

Ghi vào một tệp

Ví dụ tiếp theo là một chương trình ngắn mà tôi đã sử dụng để tạo một số dữ liệu ngẫu nhiên cho tệp dữ liệu temps.txt.

import random

f = open('temps.txt','w')

for n in range(0,50):
    f.write('{:2.1f}\n'.format(random.random()*100))

f.close()

Dưới đây là một số điều cần lưu ý trong chương trình này.

  1. Chúng tôi sẽ sử dụng mô -đun ngẫu nhiên để tạo danh sách các bài đọc nhiệt độ ngẫu nhiên.
  2. Như trong ví dụ trước, chúng tôi sử dụng hàm
    1935  32.1
    1940  30.5
    1945  24.4
    1950  23
    1955  19.1
    1960  15.6
    1965  12.4
    1970  9.7
    1975  8.9
    1980  7.2
    
    7 để mở tệp. Tham số thứ hai tùy chọn cho hàm
    1935  32.1
    1940  30.5
    1945  24.4
    1950  23
    1955  19.1
    1960  15.6
    1965  12.4
    1970  9.7
    1975  8.9
    1980  7.2
    
    7 là trình xác định chế độ tệp. Vì chúng tôi đang mở tệp này để viết, chúng tôi sử dụng trình xác định chế độ 'W'.
  3. Để viết văn bản vào tệp, chúng tôi sử dụng phương thức
    ["1935","32.1"]
    
    4. Tham số chúng tôi chuyển đến
    ["1935","32.1"]
    
    4 là một chuỗi văn bản mà chúng tôi muốn ghi vào tệp. Chúng ta phải cẩn thận để đảm bảo rằng chuỗi kết thúc trong ký tự dòng mới,
    ["1935","32.1"]
    
    6, để văn bản bị hỏng dòng ở cuối.
  4. Chúng tôi sử dụng hàm
    ["1935","32.1"]
    
    7 từ mô -đun ngẫu nhiên để tạo ra một phao ngẫu nhiên trong phạm vi từ 0,0 đến 1,0. Chúng tôi nhân số ngẫu nhiên này với 100 để chia tỷ lệ lên đến phạm vi từ 0,0 đến 100.0.
  5. Như trong ví dụ trước, chúng tôi sử dụng phương thức
    ["1935","32.1"]
    
    0 để đóng tệp khi chúng tôi hoàn thành việc ghi vào tệp.

Chức năng đọc dữ liệu chung

Trong một vài ví dụ tiếp theo, chúng tôi sẽ đọc dữ liệu từ các tệp văn bản. Trong mọi trường hợp, dữ liệu sẽ được sắp xếp như một chuỗi dữ liệu với danh sách các mục dữ liệu trên mỗi dòng của tệp. Hàm Python sau đây sẽ đóng vai trò là chức năng đọc dữ liệu chung để tải dữ liệu thô từ tệp văn bản. Hàm đọc các dòng riêng lẻ của tệp đầu vào dưới dạng chuỗi văn bản và sau đó sử dụng phương thức chuỗi

["1935","32.1"]
9 để chia từng dòng thành một danh sách các chuỗi cho các mục dữ liệu riêng lẻ.

def readData(fileName):
  """Generic data reading function:
     reads lines in a text file and
     splits them into lists."""
    data = []
    with open(fileName) as f:
        for line in f.readlines():
            data.append(lineToData(line.split()))
    return data

Bước tiếp theo thường sẽ là chuyển đổi các chuỗi trong danh sách dữ liệu của chúng tôi thành định dạng dữ liệu phù hợp với ứng dụng cụ thể của chúng tôi. Ví dụ, trong chương trình ví dụ tiếp theo bên dưới, chúng tôi sẽ sao chép ví dụ hồi quy tuyến tính mà tôi đã cho thấy một vài bài giảng trở lại. Chúng tôi sẽ làm việc với một tệp đầu vào trông như thế này:

1935  32.1
1940  30.5
1945  24.4
1950  23
1955  19.1
1960  15.6
1965  12.4
1970  9.7
1975  8.9
1980  7.2

Mục đầu tiên trong danh sách dữ liệu được trả về bởi cuộc gọi đến

["1935","32.1"]
9 trong ReadData sẽ trông giống như

["1935","32.1"]

Tôi muốn chuyển đổi cặp chuỗi đó thành một tuple chứa sự kết hợp của một số nguyên và một chiếc phao. Dưới đây là một chức năng làm sạch dữ liệu đơn giản có thể thực hiện chuyển đổi đó:

def lineToData(line)
  """Converts a raw line list into an appropriate data format."""
    return (int(line[0]),float(line[1]))

def lineToData(line)
  """Converts a raw line list into an appropriate data format."""
    return (int(line[0]),float(line[1]))
1 sau đó sẽ sử dụng hàm
def lineToData(line)
  """Converts a raw line list into an appropriate data format."""
    return (int(line[0]),float(line[1]))
2 này để đặt dữ liệu ở định dạng mà chúng ta cần.

pairs = readData('farm.txt')

Chương trình hồi quy tuyến tính

Ở đây bây giờ là chương trình đọc dữ liệu dân số trang trại và thực hiện phân tích hồi quy trên dữ liệu. Lưu ý các định nghĩa chức năng giúp chúng tôi thực hiện các phần chính của tính toán hồi quy.

temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
0

Đầu ra được sản xuất bởi chương trình này là

temps = []
f = open('temps.txt')
for line in f.readlines():
    temps.append(float(line))
f.close()

lowest = temps[0]
highest = temps[0]

for t in temps:
    if t < lowest:
        lowest = t
    if t > highest:
        highest = t

print('Lowest temp = '+str(lowest))
print('Highest temp = '+str(highest))
1

Điều này trông đúng cho một hồi quy tuyến tính.

Bài tập lập trình

Viết một chương trình Python đọc hai danh sách các số nguyên từ các tệp có tên 'One.txt' và 'Two.txt' và sau đó xác định số nào từ tệp thứ nhất không xuất hiện trong tệp thứ hai. Xây dựng danh sách các số này và sau đó viết danh sách ra tệp thứ ba có tên là 'Diff.txt'.

Để gửi công việc của bạn để chấm điểm, hãy nén toàn bộ thư mục dự án của bạn vào kho lưu trữ zip và gửi cho tôi kho lưu trữ đó như một tệp đính kèm vào một thông báo email.