Write Text data
g = open ('test.txt'rt', newline=', encoding = ' Utf-8 ', errors='replace')
T is the so-called text mode that is unique to the Windows platform, except that it automatically recognizes line breaks for the Windows platform. The line break for Unix-like platforms is \ n, whereas the Windows platform uses \ r \ n Two ASCII characters to represent line breaks, and Python internally uses \ n to represent newline characters. In RT mode, Python automatically converts \ r \ n into \N.WT mode when reading text, and Python writes a file with \ r \ n to indicate a line break.
NewLine: It is not the same in UNIX and Windows (n and RN, respectively). By default, Python handles line breaks in uniform mode. In this mode, when reading the text, Python can recognize all normal line breaks and convert them to a single \ n character similar to the output, which converts the newline character \ n to the system default line feed. If you do not want this default processing, you can give the open () function The parameter newline= "
encoding is encoded.
Errors=replace ignores errors, such as if encoding ASCII, there may be errors at the time of reading, and Errors=replace ignores all the wrong characters.
Print output to a file
Print ('Hello world! ', file = f)
Use a different delimiter or line break
row = ('ACME', 50, 91.5
# Print (". Join (Row)") Typeerror:sequence Item 1:expected STR instance, int found print ('for
in Row)) #不需要这么麻烦, the following will print(*row, sep=", end ='!! end') #sep指定分隔符, end specifies what ends with ACME 50 91.5!! End
File does not exist before writing
f = open ('txt'w') #这么打开会覆盖原文件 if the original file is not new to wear
f = open (' txt ', ' x ') #用x代替w, error if file exists. Prevent overwriting source files
#但是真正的解决办法是这个
Import OS
If not OS. Path. Exists (' Somefile '):
With open (' somefile ', ' wt ') as F:
F.write (' hello\n ')
Else
Print (' File already exists! ')
Add meta information to a function
def add_test (X:int, y:int), int: Print(x + y) add_test (x=1, y=2) Print (Add_test. __annotations__) #{' y ': <class ' int ';, ' return ': <class ' int ';, ' x ': <class ' int ';
Python cookboo file and IO functions