Get the App
SLTechnology News&Howtos  ›  Development  › 

How to read and write python file stream

Shulou Source: shulou.com Published: 2022-06-01 11:37:25 09月30日 Update

This article mainly explains the "python file stream reading and writing how to operate", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "python file stream reading and writing how to operate" it!

The read and write of the file stream reads the txt file that saves the data as an array

Use try for exception discovery and use while to detect the end of the file for reading

File_to_read = raw_input ("Enter file name of tests (empty string to end program):") try: infile = open (file_to_read,'r') while file_to_read! = "": file_to_write = raw_input ("Enter output file name (.csv will be appended to it):") file_to_write = file_to_write + ".csv" outfile = open (file_to_write "w") readings = (infile.readline ()) print readings while readings! = 0: global count readings = int (readings) minimum = (infile.readline ()) maximum = (infile.readline ())

Use for to traverse each row read for one-time read and input

The data read by the program called below is

Result = list () with open ('.. / test/parameter.txt') as f: for line in f.readlines (): temp = list () # iterate through each row of elements one by one Convert it to the corresponding data b = line.strip (",] ["). Split (',') if (len (b) > = 5): b.pop () for an in b: a = a.replace ('[,') .replace (']' '') temp.append (float (a)) result.append (temp) # print ("temp printed midway is", temp) # print ("result added to result is", result) deletes specific characters in str

Delete the redundant string strip () at the beginning and end of the string

# remove redundant characters from the string def string_remove (): str1 = 'abc' print str1.strip () # abc str2 ='- abcdf++++' print str2.strip ('- +') # abcdf

The replace function, which deletes all strings in a string

Ss = 'old old string'ret = ss.replace (' old', 'new', 1) print (ret)

Sub function, which deletes multiple strings at the same time, where regular expressions are used

Str2 = 'abcwrt22666' # Delete all the strings, import reprint (re.sub ('[]','', str2)) # abcwrt22666 Thank you for your reading. The above is the content of "how to read and write python Files". After the study of this article, I believe you have a deeper understanding of how to read and write python files. The specific use situation still needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Characters files strings data learning one line content functions one-time elements at the same time multiple that is ideas situations arrays articles more end regular Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi macOS Apple vpn MariaDB