Python Note3 (I/O)

2017-02-23  本文已影响12人  qin7zhen

Labels: Python, Keyboard Input, Files

Ref: Python Files I/O https://www.tutorialspoint.com/python/python_files_io.htm


Keyboard Input

Enter your input: Hello Python
Received input is :  Hello Python
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is :  [10, 20, 30, 40]

Files

Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, true otherwise.
file object = open(file_name [, access_mode][, buffering])

file_name: The file_name argument is a string value that contains the name of the file that you want to access.
access_mode: The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r).
buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).

fileObject.close();
fileObject.write(string);

Example

# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
# Close opend file
fo.close()
fileObject.read([count]);

count is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Check current position
position = fo.tell();
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()
import os

rename() takes two arguments, the current filename and the new filename.
Syntax

os.rename(current_file_name, new_file_name)

Example

import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
os.remove(file_name)

Example

import os
# Delete file test2.txt
os.remove("text2.txt")

Dictionaries

Method Syntax Description
mkdir() os.mkdir("newdir") create directories in the current directory.
chdir() os.chdir("newdir") change the current directory.
getcwd() os.getcwd() displays the current working directory.
rmdir() os.rmdir('dirname') deletes the directory.
上一篇 下一篇

猜你喜欢

热点阅读