looping through a file with python - python-3.x

New to python and stuck on reading a file...
I want to search a file for data using python3.
I have a data file that looks like this:
hostname,timestamp,#of CPUs,memory,cpu,disk
hostname1,07311906,1,4.84%,74%,0.45%
hostname2,07311906,2,3.84%,24%,0.45%
hostname1,07311907,1,4.85%,74%,0.49%
hostname2,07311907,2,4.64%,44%,0.30%
hostname1,07311908,1,5.20%,74%,0.78%
hostname2,07311908,2,4.44%,54%,0.40%
I'd like to cycle through a config file like this pseudo code:
for i in server.list do
<graph the data server i for the month of `date %m`>
done
The end goal is loop through my data file and do processing for each server in a list.

You can use with open() in python like this:
with open(filename, 'r') as fileContent:
listOfLines = fileContent.readlines()
Now you will have a list of every line inside of the file.
Probably also helpful would be:
for row in listOfLines:
curData = row.split(',')
This will split the content of the row at every "," and return a list.
After that you can work with the data.

Related

How can I pass a excel/csv file as a function parameter?

How can I pass a excel/csv file as a function parameter?
I have wrote a piece of code to copy content from one excel file to another excel file. Now I want to define it as a function so I just have to mention file name from which I want to transfer data to my existing file.
Thanks a lot in advance.
I am very new to Python Programming, and looking forward to learn a lot.
def feed_input_file(InputFile):
InputFile = "D:\\Python_Projects\\ABC.xlsx" #(I am passing Input file at the moment but I don't wanna pass it here)
#( Here I am trying to call my function parameter value)
Workbook1 = xl.load_workbook(feed_input_file(InputFile))
............
Still not quite sure what you are trying to do but if you want to create a function that will take a filename as an argument you could try something along the lines of:
def processFile(fn:str):
#Reads in the contents of file specified by fn
content = ''
with open(fn, 'a') as f:
data = f.read()
#Do something with data here to create content
return content
Then in your main part of the script
for filename in listofFiles:
fle_out = processFile(filename
#Do something here with file contents

Deleting a particular column/row from a CSV file using python

I want to delete a particular row from a given user input that matches with a column.
Let's say I get an employee ID and delete all it's corresponding values in the row.
Not sure how to approach this problem and other sources suggest using a temporary csv file to copy all values and re-iterate.
Since these are very primitive requirements, I would just do it manually.
Read it line by line - if you want to delete the current line, just don't write it back.
If you want to delete a column, for each line, parse it as csv (using the module csv - do not use .split(',')!) and discard the correct column.
The upside of these solutions is that it's very light on the memory and as fast as it can be runtime-wise.
That's pretty much the way to do it.
Something like:
import shutil
file_path = "test.csv"
# Creates a test file
data = ["Employee ID,Data1,Data2",
"111,Something,Something",
"222,Something,Something",
"333,Something,Something"]
with open(file_path, 'w') as write_file:
for item in data:
write_file.write(item + "\n")
# /Creates a test file
input("Look at the test.csv file if you like, close it, then press enter.")
employee_ID = "222"
with open(file_path) as read_file:
with open("temp_file.csv", 'w') as temp_file:
for line in read_file:
if employee_ID in line:
next(read_file)
temp_file.write(line)
shutil.move("temp_file.csv", file_path)
If you have other data that may match the employee ID, then you'll have to parse the line and check the employee ID column specifically.

Merge line in csv file python

I have this in csv file:
Titre,a,b,c,d,e
01,jean,paul,,
01,,,jack,
02,jeanne,jack,,
02,,,jean
and i want :
Titre,a,b,c,d,e
01,jean,paul,jack,
02,jeanne,jack,,jean
can you help me ?
In general, a good approach is to read the csv file and iterate through the rows using Python's CSV module.
CSV will create an iterator that will let you loop through your file like this:
import csv
with open('your filename.csv', 'r') as infile:
reader = csv.reader(infile)
for line in reader:
for value in line:
# Do your thing
You're going to need to construct a new data set that has different properties. The requirements you described:
Ignore any empty cells
Any time you encounter a row that has a new index number, add a new row to your new data set
Any time you encounter a row that has an index number you've seen before, add it to the row that you already created (except for that index number value itself)
I'm not writing that part of the code for you because you need to learn and grow. It's a good task for a beginner.
Once you've constructed that data set, it will look like this:
example_processed_data = [["Titre","a","b","c","d","e"],
["01","jean","paul","jack"],
["02","jeanne","jack","","jean"]]
You can then create a CSV writer, and create your outfile by iterating over that data, similarly to how you iterated over the infile:
with open('outfile.csv', 'w') as outfile:
writer = csv.writer(outfile)
for line in example_processed_data:
writer.writerow(line)
print("Done! Wrote", len(example_processed_data), "lines to outfile.csv.")

python: output a list to a csv file

I am trying to write my_list to a csv file like below:
import csv
myfile = open('my_list.csv', 'w')
wr = csv.writer(myfile)
print(len(my_list))
wr.writerow(my_list)
my_list has length 1000. Then the output of the above code is:
1000
10001
The output my_list.csv looks fine. But I am wondering why it print out 10001 on the screen? What does it mean?
It looks like you are doing this in the Python console. When you print len(my_list), it will print 1000. Next, you use wr.writerow(). It will write the row to the file and then return the current position in the file. Since it just wrote 1000 lines, the file position is at 1001 so that the next line written will not overwrite anything. In the Python console, the value that is returned is printed. If you were to execute a file with the same script, you wouldn't see that number.

Comparing input against .txt and receiving error

Im trying to compare a users input with a .txt file but they never equal. The .txt contains the number 12. When I check to see what the .txt is it prints out as
<_io.TextIOWrapper name='text.txt' encoding='cp1252'>
my code is
import vlc
a = input("test ")
rflist = open("text.txt", "r")
print(a)
print(rflist)
if rflist == a:
p = vlc.MediaPlayer('What Sarah Said.mp3')
p.play()
else:
print('no')
so am i doing something wrong with my open() or is it something else entirely
To print the contents of the file instead of the file object, try
print(rflist.read())
instead of
print(rflist)
A file object is not the text contained in the file itself, but rather a wrapper object that facilitates operations on the file, like reading its contents or closing it.
rflist.read() or f.readline() is correct.
Read the documentation section 7.2
Dive Into Python is a fantastic book to start Python. take a look at it and you can not put it down.

Resources