python file in read mode

Introduce the most general method to read a text file python

  1. Get file path

File path includes absolute and relative paths. It refers to an absolute path starting from the root folder

'E:\\a.txt'

Above absolute path, file paths under all window, features a double backslash "\", in addition to pay attention behind the "E" of ":."

All file names and paths are not starting from the root folder, it is assumed in the current working directory, the relative path is relative to the current working directory of the program. Gets the current working directory is available at the code:

>>> import os
>>> os.getcwd()
'C:\\Python34'

The current working path refers to the path currently being prepared by ".py" scripts are located.

Os.path.isfile can check the validity of the current path in interactive mode.

>>> os.path.isfile('C:\\Windows\\System32')
False

ps: When you create a file, not the file name suffix added, note the difference between the following two files.

The second was my mistake when you enter the file path to open the file, it has been an error, and it is difficult to find the cause.

  1. open a file

with open ( 'pi_digits.txt') as file_object:
the procedure described above open () class is used to open the file and returns a file object.

The reason for using with keywords is, python will help you close the file at the appropriate time, instead of calling close () close the file.

  1. Read the file

After opening the file, you can read the files.
You can read the entire file

contents = file_object.read()
print(contents)

Can also be read line by line

filename = 'pi_digits.txt'
with open(filename) as file_object:
  for line in file_object:
    print(line)

Note: When reading a text file, python to which all are interpreted as text strings.

You can also create a list containing each line of the file contents, and then the contents of files stored in the list to operate.

filename = 'pi_digits.txt'
with open(filename) as file_object:
   lines = file_object.readlines()
for line in lines:
   print(line.rstrip())

Reproduced in: https: //www.jianshu.com/p/d10ea22a4d50

Guess you like

Origin blog.csdn.net/weixin_34014277/article/details/91142082