Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- ''' Shebang so we can make this exe on linux using chmod + x <filename.py> '''
- # importing pandas
- '''https://datatofish.com/import-csv-file-python-using-pandas/'''
- import pandas as pd
- import math
- import shutil
- import os
- import glob
- m_filename = 'mytext.txt'
- m_newFile = 'output.txt'
- def readmytextfile(f):
- # read text file into pandas DataFrame
- df = pd.read_csv(f, sep=" " ,header=None ,names=["Value1", "Value2"])
- # display DataFrame
- return df
- def calculateXY(m_df):
- ''' https://www.w3schools.com/python/python_file_remove.asp '''
- # delete last files written
- if os.path.exists("output.txt"):
- os.remove("output.txt")
- # create a header for column names
- names = ["Sin Value 1", "Cos Value 2", "Sum Val 1 & Val 2"]
- # create text file to store results
- with open('output.txt', 'w') as f:
- f.write("\t".join(names))
- f.close()
- # get the number of rows
- numRows = m_df.shape[0]
- # get the umber of cols
- numCols = m_df.shape[1]
- #print these results to standard io
- for y in range(3):
- print (" ")
- print("Number of rows = " + str(numRows))
- print("Number of cols = " + str(numCols))
- # iterate through rows and perform calculations
- ''' https://docs.python.org/3/library/math.html'''
- for x in range(numRows):
- # get the sin of 1st value
- a= math.sin(m_df.iat[x,0])
- ''' convert to 3 decimal places '''
- a = float("{:.3f}".format(a))
- # get the cos of second value
- b= math.cos(m_df.iat[x,1])
- ''' convert to 3 decimal places '''
- b = float("{:.3f}".format(b))
- # store the result of addition in c
- c= a + b
- # print these results for debug
- # print (str(a) + '\t'+str(b) + '\t'+ str(c))
- # write the results to the file
- with open('output.txt', 'a+') as f:
- f.seek(0)
- data = f.read(1000)
- if len(data) > 0:
- f.write("\n")
- f.write(str(a) + '\t'+str(b) + '\t'+ str(c))
- f.close()
- def readNewfile(f):
- # read text file into pandas DataFrame
- dn = pd.read_csv(f, sep="\t")
- # display DataFrame
- return dn
- ''' this will be the main method '''
- def main():
- # clear console screen
- os.system('clear')
- m_dataframe = readmytextfile(m_filename)
- print(" ")
- print("Original file values")
- for j in range(3):
- print(" ")
- print(m_dataframe)
- calculateXY(m_dataframe)
- n_dataframe = readNewfile(m_newFile)
- for j in range(3):
- print(" ")
- print("Results calculated from myfile.txt")
- print(" " )
- print(n_dataframe)
- print ("Creating csv file named output.csv")
- '''https://docs.python.org/3/library/shutil.html'''
- shutil.copyfile('output.txt', 'output.csv')
- print("Showing files in directory " )
- '''https://datagy.io/list-files-os-glob/'''
- print(glob.glob("*.*"))
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement