Question

( Python Program) explain how Input/Output data files work in a Python program, and how you...

( Python Program) explain how Input/Output data files work in a Python program, and how you would use a loop to process input and/or output. Define the differences in a field, record and file, and define what an exception is.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Reading from a file

There are three ways to read from a file.

  • read([n])
  • readline([n])
  • readlines()

Note: that n is the number of bytes to be read.

Create a file as below:

1st line
2nd line
3rd line
4th line
5th line

Let's see what each read method does:

my_file=open("D:\\new_dir\\multiplelines.txt","r")
my_file.read()

The read() method just outputs the entire file if number of bytes are not given in the argument. If you execute my_file.read(3), you will get back the first three characters of the file

my_file=open("D:\\new_dir\\multiplelines.txt","r")
my_file.read(3)

readline(n) outputs at most n bytes of a single line of a file. It does not read more than one line.

my_file.close()
my_file=open("D:\\new_dir\\multiplelines.txt","r")
#Use print to print the line else will remain in buffer and replaced by next statement
print(my_file.readline())
# outputs first two characters of next line
print(my_file.readline(2))

Use the close() method with file handle to close the file. When you use this method, you clear all buffer and close the file.

my_file.close()

You can use a for loop to read the file line by line:

my_file=open("D:\\new_dir\\multiplelines.txt","r")
#Use print to print the line else will remain in buffer and replaced by next statement
for line in my_file:
    print(line)
my_file.close()

The readlines() method maintains a list of each line in the file:

my_file=open("D:\\new_dir\\multiplelines.txt","r")
my_file.readlines()

Writing to a file

You can use three methods to write to a file in Python:

  • write(string) (for text) or write(byte_string) (for binary)
  • writelines(list)

Let's create a new file within a folder in the "D" drive. Following will create a new file in the specified folder because it does not exist. Remember to give correct path with correct filename otherwise you will get error:

Create a notepad file and write some text in it. Make sure to save file as .txt and save it to the working directory of Python.

my_file_handle=open("mynewtextfile.txt")
my_file_handle.read()
new_file=open("D:\\new_dir\\newfile.txt",mode="w",encoding="utf-8")
new_file.write("Writing to a new file\n")
new_file.write("Writing to a new file\n")
new_file.write("Writing to a new file\n")
new_file.close()

Now let's write a list to this file with a+ mode:

fruits=["Orange\n","Banana\n","Apple\n"]
new_file=open("D:\\new_dir\\newfile.txt",mode="a+",encoding="utf-8")
new_file.writelines(fruits)
for line in new_file:
    print(line)
new_file.close()

Note that reading from a file does not print anything because the file cursor is at the end of the file. To set the cursor at the beginning, you can use the seek() method of file object:

cars=["Audi\n","Bentely\n","Toyota\n"]
new_file=open("D:\\new_dir\\newfile.txt",mode="a+",encoding="utf-8")
for car in cars:
    new_file.write(car)
print("Tell the byte at which the file cursor is:",new_file.tell())
new_file.seek(0)
for line in new_file:
    print(line)

The tell() method of file object tells at which byte the file cursor is located. In seek(offset,reference_point) the reference points are 0 (the beginning of the file and is default), 1 (the current position of file) and 2 (the end of the file).

Let's try out passing another reference point and offset and see the output:

new_file.seek(4,0)
print(new_file.readline())
new_file.close()

Note the use of .seek() and .truncate(): the argument in .truncate() is 5 that says that truncate the file till 5 bytes of text are left. And output shows exactly 5 bytes of text left including space. You are only left with next() method so let's complete this section of the tutorial! Here you are using same file created above with name multiplelines.txt.

End-relative seeks such as seek(-2,2) are not allowed if file mode does not include 'b', which indicates binary format. Only forward operations such seek(0,2) are allowed when file object is dealt as text file.

file=open("D:\\new_dir\\multiplelines.txt","r")
for index in range(5):
    line=next(file)
    print(line)
file.close()

You can think of a traditional database as an electronic filing system, organized by fields, records, and files. A field is a single piece of information; a record is one complete set of fields; and a file is a collection of records. For example, a telephone book is analogous to a file. It contains a list of records, each of which consists of three fields: name, address, and telephone number.

Python has many built-in exceptions which forces your program to output an error when something in it goes wrong.

When these exceptions occur, it causes the current process to stop and passes it to the calling process until it is handled. If not handled, our program will crash.

For example, if function A calls function B which in turn calls function C and an exception occurs in function C. If it is not handled in C, the exception passes to B and then to A.

If never handled, an error message is spit out and our program come to a sudden, unexpected halt.

Add a comment
Know the answer?
Add Answer to:
( Python Program) explain how Input/Output data files work in a Python program, and how you...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a python program that prompts the user for the names of two text files and...

    Write a python program that prompts the user for the names of two text files and compare the contents of the two files to see if they are the same. If they are, the scripts should simply output “Yes”. If they are not, the program should output “No”, followed by the first lines of each file that differ from each other. The input loop should read and compare lines from each file. The loop should break as soon as a...

  • Questions 1. How to create a comment in python? 2. The way to obtain user input...

    Questions 1. How to create a comment in python? 2. The way to obtain user input from command line 3. List standard mathematical operators in python and explain them 4. List comparison operators in python 5. Explain while loop. Give example 6. Explain for loop. Give example 7. How to create infinite loop? And how to stop it? 8. Explain a built-in function ‘range’ for ‘for’ loop 9. Explain break statement 10. Explain continue statement 11. Explain pass statement 12....

  • Write a python program to handle data from/to files (open, read/write, delete to handle data). It...

    Write a python program to handle data from/to files (open, read/write, delete to handle data). It uses exception handling – try and except to catch and handle exceptions.

  • Objective: Use input/output files, strings, and command line arguments. Write a program that processes a text...

    Objective: Use input/output files, strings, and command line arguments. Write a program that processes a text file by removing all blank lines (including lines that only contain white spaces), all spaces/tabs before the beginning of the line, and all spaces/tabs at the end of the line. The file must be saved under a different name with all the lines numbered and a single blank line added at the end of the file. For example, if the input file is given...

  • UNIX is all about manipulating files and input/output streams fluidly, so it is important to get a strong grasp of how...

    UNIX is all about manipulating files and input/output streams fluidly, so it is important to get a strong grasp of how this fundamentally works at the system call level to understand higher-level system programming concepts. Every program automatically has three file descriptors opened by the shell standard input standard output standard error 1 2 One can use read and write other open file. Normally, standard input and output on the terminal are line-buffered, so, for example, the specified number of...

  • Opening Files and Performing File Input 1 V/ Flowers.cpp This program reads nanes of flowers and ...

    Opening Files and Performing File Input in C++ Opening Files and Performing File Input 1 V/ Flowers.cpp This program reads nanes of flowers and whether they are grown in shade or sun from an input 2 file and prints the information to the user's screen. 3 Input: flowers.dat 41 Output: Names of flowers and the words sun or shade Summary In this lab, you open a file and read input from that file in a prewritten C++ program. The program...

  • In Python Please! 16.42 Lab 13B: Palindromes with Files Overview This is a demonstration of reading...

    In Python Please! 16.42 Lab 13B: Palindromes with Files Overview This is a demonstration of reading and writing files. Objectives Be able to read from an input file, perform string manipulation on each line of the file, and write to an output file. Provided input file: A single input file named myinput.txt is provided that contains a few lines of text. bob sees over the moon never odd or even statistics dr awkward Provided output file: A single output file...

  • C++ (1) Write a program to prompt the user for an input and output file name....

    C++ (1) Write a program to prompt the user for an input and output file name. The program should check for errors in opening the files, and print the name of any file which has an error, and exit if an error occurs. For example, (user input shown in caps in first line, and in second case, trying to write to a folder which you may not have write authority in) Enter input filename: DOESNOTEXIST.T Error opening input file: DOESNOTEXIST.T...

  • Write a program in python that asks the user to input a sentence. The program will...

    Write a program in python that asks the user to input a sentence. The program will ask the user what two letters are to be counted. You must use a “for” loop to go through the sentence & count how many times the chosen letter appears in the sentence. You are not allowed to use python built-in function "count()" or you'll get a Zero! Output will show the sentence, the letter, and the number of times the letter appears in...

  • 2. Write a program to read two lists of names from two input files and then...

    2. Write a program to read two lists of names from two input files and then match the names in the two lists using Co-sequential Match based on a single loop. Output the names common to both the lists to an output file, In Java

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT