Python reads txt, CSV, and Excel files

Source: Internet
Author: User

One, python read txt file: (Idea: First open the file, read the file, and finally with a for loop output content)

fp = open (' Test.txt ', ' R ')

lines = Fp.readlines ()

Fp.close ()

For line in lines:

Username = Line.split (', ') [0]

Password = line.split (', ') [1]

Note: The first sentence is to open the text file as read-only, and the second is to read all rows of data (read: reads the entire file; ReadLine: Reads a row of data); Finally, make sure to close the file. It will eventually return a list of data that can be read one after another through a for loop. such as Username,password. This time by splitting the split method, you can finally get username password, so you can be in the automation of parameterization.

Second, Python read csv file

Import CSV
Date =csv.reader (open (' Test.csv ', ' r '))
For test in Date:
Print test

Print Test[0]

Note: You need to import the CSV package first, then read the content through the reader method, and eventually return a list. To select a column of data, you only need to make a list subscript

Third, Python reads Excel

Need to install the XLRD module first

Account Password Note

Import xlrd

Book=xlrd.open_workbook (Data_dirs () + '/system.xlsx ')

Sheet=book.sheet_by_index (0)
Print Sheet.cell_value (0,2)

Note: (0,2) represents the data for the third column in the second row, namely: remarks

(not finished, to be continued)

Python reads txt, CSV, and Excel files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.