How to read from a file in C Programming

/*
* Program to read from files
* From the book: C Programming Visual Quickstart Guide
*/


#include <stdio.h>

/*
* Set the file path and name as a C pre-processor
* macro.
*/

#define THEFILE "read_text.txt"

/*
* Begin main function.
*/

int main (void) {

/* 
* Create a file pointer.
*/

FILE *fp;


/*
* Define the required variable. Only one variable is necessary
* for this application (aside from the pointer.) The line 
* character array will store the data retrived from the text
* file. Its length (30) allows for a resonable amount of data,
* based on what we expect the text file to contain.
*/

char line[30]; 

/*
* Open the file for reading. The r mode is used to only read 
* from a file.
*/

fp = fopen(THEFILE, "r");

/* 
* Start a conditional based on the file pointer and print a
* caption. 
*/

if (fp != NULL) {

printf("The contents of the 'read_text.txt' file:\n");

/*
* Read and print the file's contents in a loop.
* This loop will continue to use the fgets()
* function to read in from the file as long as it 
* can (which is until it reaches the file's end.) 
* With each iteration of the loop, the data read with
* fgets() is assigned to a line variable, which is then
* printed as a simple string.
*/

while (fgets(line, sizeof(line), fp)) {

printf("%s", line);

}

/*
* Complete the fp conditional.
*/

} else {

printf("The file could not be opened.\n");

/*
* Exit the function/application.
*/

return 1; 

}

/*
* Close the file.
*/

if (fclose(fp) != 0) {

printf("The file could not be closed.\n");

}

/* 
* Complete the main function.
*/

getchar();
return 0;

}

How to write to a file in C Programming

/* 
* Program that writes to a text file
* From the book: Visual Quickstart Guide C Programming
*
* The record_weather application takes three user input values
* (a date, the day's high tempature, and the day's low tempature)
* and writes them to a text file.
*/



#include <stdio.h>

/*
* Set the file path and name as a C preprocessor macro.
*/

#define THEFILE "weather.txt"

/* 
* Begin main function.
*/

int main(void) {

/*
* Create a file pointer.
*/

FILE *fp;

/*
* Define the required variables. The first two variables are
* integers that will store the entered high and low tempatures.
* The data variable is a character array to store dates in the 
* format. YYYY-MM-DD.
*/

int high, low;

char date[11];

/*
* Open the file for appended writing. By using an a, each new
* record will be appended to the end of the file, rather than 
* wipping out any existing data.
*/

fp = fopen(THEFILE, "a");

/*
* Start a condional bases on the file pointer and prompt the user. 
* If the file can be opened, then the user will be promplted for
* the required information.
*/

if (fp != NULL) {

printf("Enter a date, the high tempature, and the low tempature.\n(YYYY-MM-DD ## ###): ");

/*
* Handle the keyed input. Using the scanf() function, the 
* application attempts to read one string (of up to 10
* chracters long) and two integers from the standard input. 
* The string will be stored in date, which as a character
* array, can be listed directly. The two integer values go
* into high and low, which as numbers must be referenced in
* their address form (&). If scanf() successfully read in
* three items, the user entered the information properly,
* so the conditional checks if the returned value is equal 
* to 3. 
*/

if (scanf ("%10s %d %d", date, &high, &low) == 3) {

/*
* Write the data  the text file. The fprintf() function
* will write the values to the text file. The formatting
* is simple: seperate eac value by a space and ending with
* a newline.
*/

fprintf(fp, "%s %d %d\n", date, high, low);

/*
* Complete the scanf() conditional. The first message
* completes the condtional if scanf() worked, 
* indicating that the data was written to the file. 
* If scanf() did not return a value of 3, the input was
* not of the proper format and the second message is
* printed on the screen.
*/

printf ("The data has been written.\n");

/*
* Complete the fp conditional. If the application could
* not open the file for writing, there's no reason to
* continue. Because functions always stop running after
* a return staion this effectively stops the application. 
*

} else {

printf("The data was not in the promper format.\n");

}

} else {

printf("The file cound not be opened.\n");

return 1;

}

/*
* Close the file.
*/

if (fclose(fp) != 0) {

printf ("The file count not be close.\n");

} 

/*
* Complete main function
*/

getchar();
getchar();
return 0;

}

How to get current date and time in Python Programming

from datetime import datetime

now = datetime.now()

current_year = now.year

current_month = now.month

current_day = now.day

print(now)

print(now.year)

print (now.month)

print(now.day)

print('%s/%s/%s' % (now.month, now.day, now.year))

print('%s:%s:%s' % (now.hour, now.minute, now.second))

print("%s/%s/%s %s:%s:%s" % (now.month,now.year,now.year,now.hour, now.minute, now.second))

How to bind an event with an event handler with Tkinter with Python 3

# Click Counter
# From the book: Python Programming for the Absolute Beginner
# Demonstrates binding an event with an event handler

from tkinter import *

class Application(Frame):
    """ GUI application which counts button clicks. """ 
    def __init__(self, master):
        """ Initialize the frame. """
        Frame.__init__(self, master)
        self.grid()
        self.bttn_clicks = 0    # the number of button clicks
        self.create_widget()

    def create_widget(self):
        """ Create button which displays number of clicks. """
        self.bttn = Button(self)
        self.bttn["text"]= "Total Clicks: 0"
        self.bttn["command"] = self.update_count
        self.bttn.grid()

    def update_count(self):
        """ Increase click count and display new total. """
        self.bttn_clicks += 1
        self.bttn["text"] = "Total Clicks: " + str(self.bttn_clicks)
          
# main
root = Tk()
root.title("Click Counter")
root.geometry("250x50")

app = Application(root)

root.mainloop()

How to use a button widget in Tkinter with Python 3

# Lazy Buttons
# From the book: Python Programming for the Absolute Beginner
#
# Demonstrates creating buttons

from tkinter import *

# create a root window
root = Tk()
root.title("Lazy Buttons")
root.geometry("250x150")

# create a frame in the window to hold other widgets
app = Frame(root)
app.grid()

# create a button in the frame
bttn1 = Button(app, text = "I do nothing!")
bttn1.grid()

# create a second button in the frame
bttn2 = Button(app)
bttn2.grid()
bttn2.configure(text = "Me too!")

# create a third button in the frame
bttn3 = Button(app)
bttn3.grid()
bttn3["text"]= "Same here!"

# kick off the root window's event loop
root.mainloop()

How in use a label widget in Tkinter with Python 3

# Labeler
# From the book: Python Programming for the Absolute Beginner
#
# Demonstrates a label

from tkinter import *

# create the root window
root = Tk()
root.title("Labeler")
root.geometry("250x100")

# create a frame in the window to hold other widgets
app = Frame(root)
app.grid()

# create a label in the frame
lbl = Label(app, text = "I'm a label!")
lbl.grid()

# kick off the window's event loop
root.mainloop()

How to make a simple gui window in Python using the tkinter module

# Simple GUI
# From the book: Python Programming for the Absolute Beginner
#
# Demonstrates creating a window with tkiner module


# The Tkinter module is named Tkinter (capital "T") in python 2.x,
# and tkinter (lowercase "t") in python 3.x.
# from Tkinter import * (in 2.x)

from tkinter import * # (in 3.x)

# To create a root window, you instantiate an object of the tkinter class Tk.
# Notice that you do not have to prefix the module name, tkinter to the class
# name, Tk. You can directly access any part of the tkinter module without having
# to use the module name. You only have one root window in a tkinter program. If
# you create more than one, you're bound to freeze up your program as both root
# windows fight for control

root = Tk()

# Modify the window, The title() method sets up the title of the root window. All you
# have to do is pass the title you want to display as a string. The geometry() method
# sets the size of the root window. The method takes a string (and not integers) that
# represents the widow's width and height, seperated by the 'x' character.

root.title("Simple GUI")
root.geometry("400x400")

# Kick off the window's event-loop. The window stays open, waiting to handle events.
# The window is a full-fledged window that you can resize, minimize, and close.
root.mainloop()

Python Tkinter Tips

Running a Tkinter program directly from IDLE will cause either your program or IDLE to lock up. The simplest solution is to run your Tkinter program directly. In Windows, you can do this simple by double-clicking your program’s icon.

Although you can run a Tkinter program by double-clicking its icon, you’ll have a problem if the program contains an error — your console window will close before you can read the error message. Under Windows, you can create a batch file that runs your program and pauses once the program ends, keeping the console window open so you can see any error message. For example, if your program is simple_gui.py, just create a batch file comprised of the two lines:

simple_gui.py
pause

Then run the batch file by double-clicking its icon.

To create a batch file:
  1. Open a text editor such as Notepad
  2. Type your text
  3. Save the file with a .bat extension (such as simple_gui.bat) and make sure there is no .txt extension after the .bat

You may think the console window is just an eyesore, but don’t be so quick to dismiss it. The console window can provide valuable feedback when your Tkinter program produces errors.

Also don’t close the console window because that will close your GUI program along with it.

Once you get your GUI programming running perfectly, you may want to suppress its accompanying console window. On a Windows machine, the easiest way to do this is to change the extension of your program from a py to a pyw.

From: Python Programming for the Absolute Beginner