1657300980
Python có một trong những triển khai đọc và ghi tệp đơn giản nhất. Nó có thể là từ việc tạo các tài liệu văn bản đơn giản đến phân tích nhật ký nội bộ của máy chủ. Tất cả các tác vụ đó đều yêu cầu các lệnh đọc và ghi tệp thiết yếu.
Trong bài viết này, chúng ta sẽ xem xét tất cả các cách có thể có trong Python để đọc từng dòng một tệp. Python chứa các hàm được xác định trước để xử lý tệp. Do đó, chúng tôi sẽ không có bất kỳ phụ thuộc bên ngoài nào.
Bạn thử các cách triển khai sau trên trình duyệt của mình tại đây .
Phương thức Python readlines()
là một hàm được xác định trước. Khi gọi, nó trả về cho chúng ta một kiểu danh sách bao gồm mỗi dòng từ tài liệu dưới dạng một phần tử.
Cú pháp - filename.readlines()
Tham số - hint
. Đây là một tham số tùy chọn đề cập đến số byte tối đa được trả về. Giá trị mặc định là -1, trả về tất cả các byte.
Trả về - Một kiểu danh sách bao gồm nội dung tệp dưới dạng các phần tử danh sách.
Hãy xem ví dụ sau.
Tài liệu văn bản sau đây sẽ được lấy làm ví dụ.
myFile = open("PythonPool.txt", "r")
print(myFile.readlines())
Đầu ra
['Welcome to PythonPool! Source for Free Python Material.']
Chúng ta có thể sử dụng vòng lặp for để đọc từng dòng tệp trong Python. Hàm open () trả về một đối tượng có thể lặp lại trong khi mở tài liệu. Sử dụng đối tượng, chúng ta có thể lặp lại vòng lặp for để đọc các dòng. Hãy xem một ví dụ.
Đây là tệp văn bản mà chúng tôi sẽ sử dụng
myFile = open("PythonPool.txt", "r")
for eachLine in myFile:
print(eachLine)
Đầu ra
Welcome to PythonPool! Source for Free Python Material.
This is line 2
This is line 3
Hãy xem xét một phương thức khác trong Python để đọc từng dòng một tệp.
Trong Python, trình quản lý ngữ cảnh cho phép người dùng quản lý các tệp bằng từ khóa “with” cùng với các phương thức Tệp I / O. Nó giám sát tệp đang được mở và đóng ngay sau khi các hoạt động tệp kết thúc thực thi.
Trong phần trình diễn này, chúng tôi sẽ sử dụng trình quản lý ngữ cảnh cùng với For Loop
Đây là tài liệu mẫu mà chúng tôi sẽ sử dụng:
with open("/content/PythonPool.txt") as myFile:
myFileContents = myFile.read()
print(myFileContents)
Đầu ra
Welcome to PythonPool! Source for Free Python Material.
This is line 2
This is line 3
Sử dụng genfromtxt()
tính năng này, chúng tôi có thể đọc dữ liệu từ tệp. Hàm yêu cầu 2 tham số:
delimiter
- Bộ ký tự dùng để phân cách từng dòng.from numpy import genfromtxt
myCSV = genfromtxt('/content/sample_data/california_housing_test.csv', delimiter=',')
print(myCSV)
Đầu ra
Để đọc ngược một tệp đã cho, chúng ta sẽ sử dụng reversed()
hàm. Tham khảo minh chứng sau đây.
Tài liệu văn bản mà chúng tôi sẽ sử dụng:
for line in reversed(list(open("/content/PythonPool.txt"))):
print(line.rstrip())
Đầu ra
This is line 3
This is line 2
Welcome to PythonPool! Source for Free Python Material.
Tuy nhiên, có một vấn đề với việc triển khai này. Nếu toàn bộ tệp không thể được chứa trong bộ nhớ, chương trình trên không thành công.
Giải pháp thay thế là sử dụng file_read_backwards
mô-đun. Điều này cho phép chúng tôi đọc các tệp lớn trong bộ nhớ theo cách hoạt động hiệu quả hơn nhiều.
from file_read_backwards import FileReadBackwards
with FileReadBackwards("/content/PythonPool.txt", encoding="utf-8") as myFile:
for eachLine in myFile:
print(eachLine)
Đầu ra
This is line 3
This is line 2
Welcome to PythonPool! Source for Free Python Material.
Trong trường hợp này, chúng ta sẽ đọc nội dung tệp từ tài liệu văn bản sau vào từ điển.
Bằng cách tạo một từ điển trống, chúng ta có thể nhập các khóa và giá trị từ tệp văn bản bằng cách sử dụng .split()
hàm. Để lặp lại quá trình cho nhiều dòng, vòng lặp for được sử dụng.
prices = {}
with open("/content/SampleText.txt") as f:
for eachLine in f:
# splitting between each space character
(key, value) = eachLine.split()
prices[str(key)] = int(value)
print(prices)
Đầu ra
{'iPhone': 150000, 'Samsung': 50000, 'OnePlus': 80000, 'Oppo': 35000}
Sử dụng trình quản lý ngữ cảnh, chúng tôi có thể chuyển các bộ lọc trên mỗi dòng và loại bỏ các ký tự khoảng trắng dòng mới. Tham khảo cách thực hiện sau đây.
Đây là tài liệu được đề cập:
with open("/content/PythonPool.txt") as myFile:
lines = filter(None, (eachLine.rstrip() for eachLine in myFile))
for i in lines:
print(i)
Đầu ra
Welcome to PythonPool! Source for Free Python Material.
This is line 2
This is line 3
Trong các tệp rất lớn, bộ nhớ có thể là một vấn đề. Do đó, chúng ta có thể cần các phụ thuộc bên ngoài. Hãy xem cách chúng ta có thể đọc các dòng từ một tệp bằng mô-đun Pandas .
Sử dụng chuncksize
tham số của .read_csv()
, chúng tôi chỉ có thể đọc số tiền nói trên.
Mỗi dòng được đặt vào danh sách được xác định trước.
import pandas as pd
lines=[]
for eachLine in pd.read_csv('/content/sample_data/california_housing_test.csv', encoding='utf-8', header=None, chunksize=1):
lines.append(eachLine.iloc[0,0])
print(lines)
Đầu ra
['longitude', -122.05, -118.3, -117.81, -118.36, -119.67, -119.56, -121.43
...
...
...
...
117.12, -119.63]
Với sự trợ giúp của gói Python XML, chúng tôi có thể đọc các tệp XML theo từng dòng.
import xml.etree.ElementTree as ET
tree = ET.parse('/content/myXML.xml')
bookCatalog = tree.findall('book')
print('Number of Books:', len(bookCatalog))
for eachBook in bookCatalog:
print('Author: ', eachBook.find('author').text)
print('Title: ', eachBook.find('title').text)
print('Price: ', eachBook.find('price').text)
Đầu ra
Number of Books: 10
Author: Gambardella, Matthew
Title: XML Developer's Guide
Price: 44.95
...
...
Author: O'Brien, Tim
Title: Microsoft .NET: The Programming Bible
Price: 36.95
JSON hoặc JavaScript Object Notation là một định dạng trong đó dữ liệu được hoán đổi cho nhau. Hầu hết các API gửi và nhận yêu cầu ở định dạng JSON. Do đó, điều quan trọng là chúng ta phải học cách quản lý các tệp như vậy trong Python.
Trình diễn sau đây cho thấy cách chúng ta có thể đọc các tệp JSON theo từng dòng.
Với sự trợ giúp của thư viện chuẩn JSON trong Python, chúng tôi có thể làm việc với các tệp JSON.
Đây là tài liệu JSON mà chúng tôi sẽ làm việc với:
import json
data = [ ]
with open("/content/myJSON.txt") as myFile:
for eachLine in myFIle:
data.append(json.loads(eachLine))
print(data)
Đầu ra
Mango, Large, Yellow
Làm cách nào để tôi chỉ đọc dòng thứ hai trong Python?
Trong trình quản lý ngữ cảnh, bạn có thể cung cấp giá trị chỉ mục trên readlines()
hàm như sau:with open(fileName) as fileVar:
variable = fileVar.readlines()[1]
print(variable)
Làm cách nào để đọc từng dòng tài liệu PDF bằng Python?
Với sự trợ giúp của mô-đun PyPDF2, chúng tôi có thể xử lý các tệp PDF trong Python.import PyPDF2
pdfFileObj = open('samplepdf.pdf','rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
Làm cách nào để đọc từng dòng tệp .rpt bằng Python
Sử dụng readlines()
, bạn có thể đọc từng dòng của tệp báo cáo.myReport = open("/content/report.rpt", "r")
repLines = myReport.readlines()
Chúng tôi đã xem xét cách chúng tôi có thể đọc từng dòng tệp trong Python bất kể định dạng đó có thể là gì. Nhiều ví dụ khác nhau cho tệp văn bản, tệp JSON, tệp CSV và tệp XML đã được xem xét.
Nguồn: https://www.pythonpool.com
1619510796
Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.
Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is
Syntax: x = lambda arguments : expression
Now i will show you some python lambda function examples:
#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map
1626775355
No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas.
By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities.
Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly.
Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.
Robust frameworks
Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions.
Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events.
Simple to read and compose
Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building.
The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties.
Utilized by the best
Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player.
Massive community support
Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions.
Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking.
Progressive applications
Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.
The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.
Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential.
The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.
#python development services #python development company #python app development #python development #python in web development #python software development
1602968400
Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?
In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.
Swapping value in Python
Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead
>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName
>>> print(FirstName, LastName)
('Jordan', 'kalebu')
#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development
1602666000
Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.
In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.
Heres a solution
Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.
But How do we do it?
If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?
The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.
There’s a variety of hashing algorithms out there such as
#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips
1657300980
Python có một trong những triển khai đọc và ghi tệp đơn giản nhất. Nó có thể là từ việc tạo các tài liệu văn bản đơn giản đến phân tích nhật ký nội bộ của máy chủ. Tất cả các tác vụ đó đều yêu cầu các lệnh đọc và ghi tệp thiết yếu.
Trong bài viết này, chúng ta sẽ xem xét tất cả các cách có thể có trong Python để đọc từng dòng một tệp. Python chứa các hàm được xác định trước để xử lý tệp. Do đó, chúng tôi sẽ không có bất kỳ phụ thuộc bên ngoài nào.
Bạn thử các cách triển khai sau trên trình duyệt của mình tại đây .
Phương thức Python readlines()
là một hàm được xác định trước. Khi gọi, nó trả về cho chúng ta một kiểu danh sách bao gồm mỗi dòng từ tài liệu dưới dạng một phần tử.
Cú pháp - filename.readlines()
Tham số - hint
. Đây là một tham số tùy chọn đề cập đến số byte tối đa được trả về. Giá trị mặc định là -1, trả về tất cả các byte.
Trả về - Một kiểu danh sách bao gồm nội dung tệp dưới dạng các phần tử danh sách.
Hãy xem ví dụ sau.
Tài liệu văn bản sau đây sẽ được lấy làm ví dụ.
myFile = open("PythonPool.txt", "r")
print(myFile.readlines())
Đầu ra
['Welcome to PythonPool! Source for Free Python Material.']
Chúng ta có thể sử dụng vòng lặp for để đọc từng dòng tệp trong Python. Hàm open () trả về một đối tượng có thể lặp lại trong khi mở tài liệu. Sử dụng đối tượng, chúng ta có thể lặp lại vòng lặp for để đọc các dòng. Hãy xem một ví dụ.
Đây là tệp văn bản mà chúng tôi sẽ sử dụng
myFile = open("PythonPool.txt", "r")
for eachLine in myFile:
print(eachLine)
Đầu ra
Welcome to PythonPool! Source for Free Python Material.
This is line 2
This is line 3
Hãy xem xét một phương thức khác trong Python để đọc từng dòng một tệp.
Trong Python, trình quản lý ngữ cảnh cho phép người dùng quản lý các tệp bằng từ khóa “with” cùng với các phương thức Tệp I / O. Nó giám sát tệp đang được mở và đóng ngay sau khi các hoạt động tệp kết thúc thực thi.
Trong phần trình diễn này, chúng tôi sẽ sử dụng trình quản lý ngữ cảnh cùng với For Loop
Đây là tài liệu mẫu mà chúng tôi sẽ sử dụng:
with open("/content/PythonPool.txt") as myFile:
myFileContents = myFile.read()
print(myFileContents)
Đầu ra
Welcome to PythonPool! Source for Free Python Material.
This is line 2
This is line 3
Sử dụng genfromtxt()
tính năng này, chúng tôi có thể đọc dữ liệu từ tệp. Hàm yêu cầu 2 tham số:
delimiter
- Bộ ký tự dùng để phân cách từng dòng.from numpy import genfromtxt
myCSV = genfromtxt('/content/sample_data/california_housing_test.csv', delimiter=',')
print(myCSV)
Đầu ra
Để đọc ngược một tệp đã cho, chúng ta sẽ sử dụng reversed()
hàm. Tham khảo minh chứng sau đây.
Tài liệu văn bản mà chúng tôi sẽ sử dụng:
for line in reversed(list(open("/content/PythonPool.txt"))):
print(line.rstrip())
Đầu ra
This is line 3
This is line 2
Welcome to PythonPool! Source for Free Python Material.
Tuy nhiên, có một vấn đề với việc triển khai này. Nếu toàn bộ tệp không thể được chứa trong bộ nhớ, chương trình trên không thành công.
Giải pháp thay thế là sử dụng file_read_backwards
mô-đun. Điều này cho phép chúng tôi đọc các tệp lớn trong bộ nhớ theo cách hoạt động hiệu quả hơn nhiều.
from file_read_backwards import FileReadBackwards
with FileReadBackwards("/content/PythonPool.txt", encoding="utf-8") as myFile:
for eachLine in myFile:
print(eachLine)
Đầu ra
This is line 3
This is line 2
Welcome to PythonPool! Source for Free Python Material.
Trong trường hợp này, chúng ta sẽ đọc nội dung tệp từ tài liệu văn bản sau vào từ điển.
Bằng cách tạo một từ điển trống, chúng ta có thể nhập các khóa và giá trị từ tệp văn bản bằng cách sử dụng .split()
hàm. Để lặp lại quá trình cho nhiều dòng, vòng lặp for được sử dụng.
prices = {}
with open("/content/SampleText.txt") as f:
for eachLine in f:
# splitting between each space character
(key, value) = eachLine.split()
prices[str(key)] = int(value)
print(prices)
Đầu ra
{'iPhone': 150000, 'Samsung': 50000, 'OnePlus': 80000, 'Oppo': 35000}
Sử dụng trình quản lý ngữ cảnh, chúng tôi có thể chuyển các bộ lọc trên mỗi dòng và loại bỏ các ký tự khoảng trắng dòng mới. Tham khảo cách thực hiện sau đây.
Đây là tài liệu được đề cập:
with open("/content/PythonPool.txt") as myFile:
lines = filter(None, (eachLine.rstrip() for eachLine in myFile))
for i in lines:
print(i)
Đầu ra
Welcome to PythonPool! Source for Free Python Material.
This is line 2
This is line 3
Trong các tệp rất lớn, bộ nhớ có thể là một vấn đề. Do đó, chúng ta có thể cần các phụ thuộc bên ngoài. Hãy xem cách chúng ta có thể đọc các dòng từ một tệp bằng mô-đun Pandas .
Sử dụng chuncksize
tham số của .read_csv()
, chúng tôi chỉ có thể đọc số tiền nói trên.
Mỗi dòng được đặt vào danh sách được xác định trước.
import pandas as pd
lines=[]
for eachLine in pd.read_csv('/content/sample_data/california_housing_test.csv', encoding='utf-8', header=None, chunksize=1):
lines.append(eachLine.iloc[0,0])
print(lines)
Đầu ra
['longitude', -122.05, -118.3, -117.81, -118.36, -119.67, -119.56, -121.43
...
...
...
...
117.12, -119.63]
Với sự trợ giúp của gói Python XML, chúng tôi có thể đọc các tệp XML theo từng dòng.
import xml.etree.ElementTree as ET
tree = ET.parse('/content/myXML.xml')
bookCatalog = tree.findall('book')
print('Number of Books:', len(bookCatalog))
for eachBook in bookCatalog:
print('Author: ', eachBook.find('author').text)
print('Title: ', eachBook.find('title').text)
print('Price: ', eachBook.find('price').text)
Đầu ra
Number of Books: 10
Author: Gambardella, Matthew
Title: XML Developer's Guide
Price: 44.95
...
...
Author: O'Brien, Tim
Title: Microsoft .NET: The Programming Bible
Price: 36.95
JSON hoặc JavaScript Object Notation là một định dạng trong đó dữ liệu được hoán đổi cho nhau. Hầu hết các API gửi và nhận yêu cầu ở định dạng JSON. Do đó, điều quan trọng là chúng ta phải học cách quản lý các tệp như vậy trong Python.
Trình diễn sau đây cho thấy cách chúng ta có thể đọc các tệp JSON theo từng dòng.
Với sự trợ giúp của thư viện chuẩn JSON trong Python, chúng tôi có thể làm việc với các tệp JSON.
Đây là tài liệu JSON mà chúng tôi sẽ làm việc với:
import json
data = [ ]
with open("/content/myJSON.txt") as myFile:
for eachLine in myFIle:
data.append(json.loads(eachLine))
print(data)
Đầu ra
Mango, Large, Yellow
Làm cách nào để tôi chỉ đọc dòng thứ hai trong Python?
Trong trình quản lý ngữ cảnh, bạn có thể cung cấp giá trị chỉ mục trên readlines()
hàm như sau:with open(fileName) as fileVar:
variable = fileVar.readlines()[1]
print(variable)
Làm cách nào để đọc từng dòng tài liệu PDF bằng Python?
Với sự trợ giúp của mô-đun PyPDF2, chúng tôi có thể xử lý các tệp PDF trong Python.import PyPDF2
pdfFileObj = open('samplepdf.pdf','rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
Làm cách nào để đọc từng dòng tệp .rpt bằng Python
Sử dụng readlines()
, bạn có thể đọc từng dòng của tệp báo cáo.myReport = open("/content/report.rpt", "r")
repLines = myReport.readlines()
Chúng tôi đã xem xét cách chúng tôi có thể đọc từng dòng tệp trong Python bất kể định dạng đó có thể là gì. Nhiều ví dụ khác nhau cho tệp văn bản, tệp JSON, tệp CSV và tệp XML đã được xem xét.
Nguồn: https://www.pythonpool.com