Cải thiện bài viết Show 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;
Ở đâ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. Python3f = 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 data0 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 data1 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 data2 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 data5 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 data6 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 data7 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 data9 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.21 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.22 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.23 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.25 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.26 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ệpChươ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.
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ệpVí 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.
Chức năng đọc dữ liệu chungTrong 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ìnhViế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. |