Python practices with AI

How to import and read line by line text file in Python?

I shared some ideas on my website, like the simplest way of Read Files or using libraries: OSLinecache. When I asked the same question on ChatGPT I received this:

Source: chat.openai.com

AI desribed really deeply all the details:

In this example, we use a with statement, which is a context manager, to open the file. This ensures that the file is automatically closed after the with block, even if an exception occurs. Make sure to replace ‘path/to/your/file.txt’ with the actual path to your text file. The line.strip() method is used to remove the newline character (\n) at the end of each line, which is added by default during reading. You can process each line as needed inside the loop. Remember to handle exceptions (e.g., FileNotFoundError and IOError) that may occur if the file does not exist or if there are issues with reading the file.

Source: chat.openai.com

I needed to operate on data after import and I asked:
how to import only last column from text file in Python?
AI showed me another sample of a code, which I used, but modified a little to suit it my case:

file_path = 'Movies.txt'

years = []

try:
    with open(file_path, 'r') as file:
        for line in file:
            columns = line.strip().split('\t')
            year = columns[-1]
            years.append(year)
except FileNotFoundError:
    print("File not found.")
except IOError:
    print("Error while reading the file.")

Then I tested some operations on it by myself:

print(years)
print(type(years))
tpl = tuple(years[1:10])
print(tpl)
print(max(tpl),min(tpl))
print(len(tpl))
print(len(years))

import statistics

print(statistics.median(tpl))
print(statistics.median(years))

And the final inquiry to AI in this topic: how to export as an Excel file in Python?
Offered me something like this (modified to my example):

import pandas as pd
# Create a DataFrame from the list of ages
data_frame = pd.DataFrame({'ReleaseYear': years})

# Export the DataFrame to an Excel file
data_frame.to_excel('D:\ReleaseYear.xlsx', index=False)

print("Data exported to Excel successfully.")

Must say that chatGPT might be useful as long as you know, what you searching for and have some basic knowledge to understand it and modify it by yourself. And what is important nowadays, also in other categories than programming, stay strong with your own rules and standards to keep distance to all you will get from AI 🙂

[VBA Excel] Progress Bar – Learn with AI

ME: How to create a Progress Bar in VBA?

ChatGPT (Source: chat.openai.com):
Creating a progress bar in VBA involves using UserForms, which are dialog boxes that allow you to create custom interfaces. Here’s a step-by-step guide on how to create a simple progress bar in VBA:

Step 1: Open the Visual Basic for Applications (VBA) editor:

  • In Excel, press “ALT + F11” to open the VBA editor.

Step 2: Insert a UserForm:

  • In the VBA editor, click on “Insert” in the menu and choose “UserForm” to add a new UserForm to your project.

Step 3: Add Controls to the UserForm:

  • In the toolbox (if not visible, press “CTRL + T” to show it), select “ProgressBar” and draw it on the UserForm.
  • Add a Label to display the progress percentage (optional but useful for user feedback).

Step 4: Set Properties for the ProgressBar:

  • Select the ProgressBar control on the UserForm and set its “Min” and “Max” properties to 0 and 100, respectively.
  • You can also set other properties like the “Caption,” “BorderStyle,” etc., according to your preference.

Step 5: Add VBA Code for the Progress Bar:

  • Double-click on the UserForm to open the code window for the form.
  • In the code window, paste the following code:
Option Explicit

Private Sub UserForm_Activate()
    ' Initialize the progress bar
    ProgressBar1.Value = 0
End Sub

Public Sub UpdateProgressBar(ByVal percentage As Double)
    ' Update the progress bar with the given percentage
    ProgressBar1.Value = percentage
    Label1.Caption = "Progress: " & Format(percentage, "0.0") & "%"
    DoEvents ' Allow the UserForm to refresh
End Sub

Step 6: Use the Progress Bar in Your VBA Code:

  • Now you can use the progress bar in your VBA code. For example, if you have a loop and want to update the progress bar during its execution, you can do something like this:
Sub ExampleUsingProgressBar()
    Dim i As Long
    Dim totalIterations As Long
    
    totalIterations = 1000 ' Set the total number of iterations
    
    ' Show the progress bar form
    UserForm1.Show vbModeless
    
    For i = 1 To totalIterations
        ' Your code here (perform the task)
        ' ...
        
        ' Update the progress bar after each iteration
        UserForm1.UpdateProgressBar i / totalIterations * 100
    Next i
    
    ' Close the progress bar form when the task is done
    Unload UserForm1
End Sub

Step 7: Close the VBA editor and run the macro:

  • Close the VBA editor and run the macro containing the code shown in “ExampleUsingProgressBar.”

This will display the UserForm with the progress bar updating as the loop progresses, giving you a simple progress indication. Note that you can customize the progress bar appearance and behavior according to your requirements.

Source: chat.openai.com