Get the App
SLTechnology News&Howtos  ›  Development  › 

How to read and write txt files and convert csv files to pandas conditions by Python

Shulou Source: shulou.com Published: 2022-06-02 13:10:09 09月22日 Update

This article mainly introduces "Python how to read and write txt files and convert csv files and pandas conditions". In daily operation, I believe many people have doubts about how to read and write txt files and convert csv files and pandas conditions. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for everyone to answer the questions of "how to read and write txt files and convert csv files and pandas conditions". Next, please follow the editor to study!

Q1. Enter a string from the keyboard and write the string to the file record.txt.

X=input ('Please enter what to write:')

F1 = open ('record.txt','a')

F1.write (x)

Q2. The file user.txt stores the user's id,name and age information, and programs to count the number of users aged about 20.

For example, the user.txt file format is:

1 jack 20

2 john 22

3 ceily 19

4 bill 25

Import pandas as pd

Import csv

# write to txt

F2=open ('user.txt','a')

L = ['id name age','\ n1 jack 20'\ n2 john 22'\ n3 ceily 19'\ n4 bill 25']

F2.writelines (l)

# converting txt to csv and processing

Df=pd.read_csv ('user.csv')

Print (df)

Print (sum (df.age.apply (lambda x df.age.apply 1 if abs (x Mel 20))

Tags: Files conditions learning characters strings more formats users processing help statistics programming input utility next number of people flow of people information content hospital Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Xiaomi Shulou Tech Info Redmi Shulou Information