Answers for "how to parse text file in python"

29

get text from txt file python

with open ("data.txt", "r") as myfile:
    data = myfile.read().splitlines()
Posted by: Guest on December-10-2020
23

python read file

# Basic syntax:
with open('/path/to/filename.extension', 'open_mode') as filename:
  file_data = filename.readlines()	# Or filename.read() 
# Where:
#	- open imports the file as a file object which then needs to be read
#		with one of the read options
#	- readlines() imports each line of the file as an element in a list
#	- read() imports the file contents as one long new-line-separated 
#		string
#	- open_mode can be one of:
#		- "r" = Read which opens a file for reading (error if the file 
#			doesn't exist)
#		- "a" = Append which opens a file for appending (creates the 
#			file if it doesn't exist)
#		- "w" = Write which opens a file for writing (creates the file 
#			if it doesn't exist)
#		- "x" = Create which creates the specified file (returns an error
#			if the file exists)
# Note, "with open() as" is recommended because the file is closed 
#	automatically so you don't have to remember to use file.close()

# Basic syntax for a delimited file with multiple fields:
import csv
with open('/path/to/filename.extension', 'open_mode') as filename:
	file_data = csv.reader(filename, delimiter='delimiter')
    data_as_list = list(file_data)
# Where:
#	- csv.reader can be used for files that use any delimiter, not just
#		commas, e.g.: '\t', '|', ';', etc. (It's a bit of a misnomer)
#	- csv.reader() returns a csv.reader object which can be iterated 
#		over, directly converted to a list, and etc. 

# Importing data using Numpy:
import numpy as np
data = np.loadtxt('/path/to/filename.extension',
				delimiter=',', 	# String used to separate values
				skiprows=2, 	# Number of rows to skip
				usecols=[0,2], 	# Specify which columns to read
				dtype=str) 		# The type of the resulting array

# Importing data using Pandas:
import pandas as pd
data = pd.read_csv('/path/to/filename.extension',
				nrows=5, 		# Number of rows of file to read
				header=None, 	# Row number to use as column names 
	            sep='\t', 		# Delimiter to use 
	            comment='#', 	# Character to split comments
				na_values=[""])	# String to recognize as NA/NaN

# Note, pandas can also import excel files with pd.read_excel()
Posted by: Guest on October-11-2020
3

reading and writing data in a text file with python

#for reading and writing data in a text file with python
#First you must have a file Open or create a new file have it loaded in memory.
# Open function to open the file "MyFile1.txt" 
# (same directory) in append mode and 
file1 = open("MyFile.txt","a") 

# store its reference in the variable file1 
# and "MyFile2.txt" in D:\Text in file2 
file2 = open(r"D:\Text\MyFile2.txt","w+") 

# Opening and Closing a file "MyFile.txt" 
# for object name file1. 
file1 = open("MyFile.txt","a") 
file1.close() 

# Program to show various ways to read and 
# write data in a file. 
file1 = open("myfile.txt","w") 
L = ["This is Delhi \n","This is Paris \n","This is London \n"] 

# \n is placed to indicate EOL (End of Line) 
file1.write("Hello \n") 
file1.writelines(L) 
file1.close() #to change file access modes 

file1 = open("myfile.txt","r+") 

print "Output of Read function is "
print file1.read() 
print

# seek(n) takes the file handle to the nth 
# bite from the beginning. 
file1.seek(0) 

print "Output of Readline function is "
print file1.readline() 
print

file1.seek(0) 

# To show difference between read and readline 
print "Output of Read(9) function is "
print file1.read(9) 
print

file1.seek(0) 

print "Output of Readline(9) function is "
print file1.readline(9) 

file1.seek(0) 
# readlines function 
print "Output of Readlines function is "
print file1.readlines() 
print
file1.close() 

# Python program to illustrate 
# Append vs write mode 
file1 = open("myfile.txt","w") 
L = ["This is Delhi \n","This is Paris \n","This is London \n"] 
file1.close() 

# Append-adds at last 
file1 = open("myfile.txt","a")#append mode 
file1.write("Today \n") 
file1.close() 

file1 = open("myfile.txt","r") 
print "Output of Readlines after appending"
print file1.readlines() 
print
file1.close() 

# Write-Overwrites 
file1 = open("myfile.txt","w")#write mode 
file1.write("Tomorrow \n") 
file1.close() 

file1 = open("myfile.txt","r") 
print "Output of Readlines after writing"
print file1.readlines() 
print
file1.close() 

Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']

Output of Readlines after writing
['Tomorrow \n']
Posted by: Guest on November-22-2019
0

parsing text in python

my_string = 'Names: Romeo, Juliet'

# split the string at ':'
step_0 = my_string.split(':')

# get the first slice of the list
step_1 = step_0[1]

# split the string at ','
step_2 = step_1.split(',')

# strip leading and trailing edge spaces of each item of the list 
step_3 = [name.strip() for name in step_2]

# do all the above operations in one go
one_go = [name.strip() for name in my_string.split(':')[1].split(',')]

for idx, item in enumerate([step_0, step_1, step_2, step_3]):
    print("Step {}: {}".format(idx, item))

print("Final result in one go: {}".format(one_go))
Posted by: Guest on August-07-2020

Code answers related to "how to parse text file in python"

Python Answers by Framework

Browse Popular Code Answers by Language