Using strings with input/output operations is a common task when working with MicroPython on Raspberry Pi Pico. In this post, we will explore how to use strings with input/output operations, including reading and writing strings to files and the console.
Reading strings from the console
The easiest way to read strings from the console is to use the built-in function input()
. This function reads a line of text from the console and returns it as a string.
name = input("Enter your name: ")
print("Hello,", name)
This code prompts the user to enter their name and then greets them by name.
Writing strings to the console
To output a string to the console, we can use the built-in function print()
. This function takes one or more arguments, converts them to strings, and outputs them to the console.
print("Hello, world!")
This code outputs the string “Hello, world!” to the console.
Writing strings to files
To write a string to a file, we need to open the file for writing and then use the write()
method to write the string to the file.
with open("output.txt", "w") as f:
f.write("Hello, world!")
This code creates a new file called “output.txt” in the current directory and writes the string “Hello, world!” to the file.
Reading strings from files
To read a string from a file, we need to open the file for reading and then use the read()
method to read the string from the file.
with open("input.txt", "r") as f:
contents = f.read()
print(contents)
This code reads the contents of a file called “input.txt” in the current directory and outputs the contents to the console.
Leave a Reply