Python输入输出

来源:互联网 发布:php成绩管理系统源码 编辑:程序博客网 时间:2024/05/17 02:59

1 从键盘读入数据:

两种基本方法:

  • raw_input

  • input

input()是把读入的数据默认为Python expression(额...中文怎么说,python表达式?)

raw_input()是把读入的数据转换成String.

所以一般时候我们用来接受用户输入的时候,都是使用raw_input()而非input().

 

两者之间的区别:

The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline):

The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you

 

在python3.0中发现使用raw_input报错,网上google下说的是3.0 和2.X的区别之一,没了raw_input改为input

例子:

D:/>python test.py
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    str = raw_input("Enter your input: ");
NameError: name 'raw_input' is not defined

 

改为input之后为:


D:/>python test.py
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    str = raw_input("Enter your input: ");
NameError: name 'raw_input' is not defined

 

 

 

2 python读写文件:

file object = open(file_name [, access_mode][, buffering])

Here is paramters detail:

  • 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 ie. 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 will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).

Here is a list of the different modes of opening a file:

ModesDescriptionrOpens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.rbOpens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.r+Opens a file for both reading and writing. The file pointer will be at the beginning of the file.rb+Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.wOpens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.wbOpens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.w+Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.wb+Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.aOpens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.abOpens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.a+Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.ab+Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

The file object atrributes:

Once a file is opened and you have one file object, you can get various information related to that file.

Here is a list of all attributes related to file object:

AttributeDescriptionfile.closedReturns true if file is closed, false otherwise.file.modeReturns access mode with which file was opened.file.nameReturns name of the file.file.softspaceReturns false if space explicitly required with print, true otherwise.

 

文件的关闭:

fileObject.close();基本例子:#!/usr/bin/python# Open a filefo = open("foo.txt", "wb")print ("Name of the file: ", fo.name)# Close opend filefo.close()3 文件的读写:

The write() Method:

The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.

The write() method does not add a newline character ('/n') to the end of the string:

Syntax:

fileObject.write(string);

#!/usr/bin/python# Open a filefo = open("foo.txt", "wb")fo.write( b'Python is a great language.');# Close opend filefo.close()读文件:fileObject.read([count]);

Here passed parameter is the number of bytes to be read from the opend 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, may be until the end of file.

关于文件的位置:

The tell() method tells you the current position within the file in other words, the next read or write will occur at that many bytes from the beginning of the file:

 

The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved.

If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position.

4 文件的命名和删除

The rename() Method:

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

Syntax:

os.rename(current_file_name, new_file_name)os.delete(file_name)5处理目录和文件相关的:

The os module provides a big range of useful methods to manipulate files and directories. Most of the useful methods are listed here:

SNMethods with Description1os.access(path, mode) 
Use the real uid/gid to test for access to path.2os.chdir(path) 
Change the current working directory to path3os.chflags(path, flags) 
Set the flags of path to the numeric flags.4os.chmod(path, mode) 
Change the mode of path to the numeric mode.5os.chown(path, uid, gid) 
Change the owner and group id of path to the numeric uid and gid.6os.chroot(path) 
Change the root directory of the current process to path.7os.close(fd) 
Close file descriptor fd.8os.closerange(fd_low, fd_high) 
Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors.9os.dup(fd) 
Return a duplicate of file descriptor fd.10os.dup2(fd, fd2) 
Duplicate file descriptor fd to fd2, closing the latter first if necessary.11os.fchdir(fd) 
Change the current working directory to the directory represented by the file descriptor fd.12os.fchmod(fd, mode) 
Change the mode of the file given by fd to the numeric mode.13os.fchown(fd, uid, gid) 
Change the owner and group id of the file given by fd to the numeric uid and gid.14os.fdatasync(fd) 
Force write of file with filedescriptor fd to disk.15os.fdopen(fd[, mode[, bufsize]]) 
Return an open file object connected to the file descriptor fd.16os.fpathconf(fd, name) 
Return system configuration information relevant to an open file. name specifies the configuration value to retrieve.17os.fstat(fd) 
Return status for file descriptor fd, like stat().18os.fstatvfs(fd) 
Return information about the filesystem containing the file associated with file descriptor fd, like statvfs().19os.fsync(fd) 
Force write of file with filedescriptor fd to disk.20os.ftruncate(fd, length) 
Truncate the file corresponding to file descriptor fd, so that it is at most length bytes in size.21os.getcwd() 
Return a string representing the current working directory.22os.getcwdu() 
Return a Unicode object representing the current working directory.23os.isatty(fd) 
Return True if the file descriptor fd is open and connected to a tty(-like) device, else False.24os.lchflags(path, flags) 
Set the flags of path to the numeric flags, like chflags(), but do not follow symbolic links.25os.lchmod(path, mode) 
Change the mode of path to the numeric mode.26os.lchown(path, uid, gid) 
Change the owner and group id of path to the numeric uid and gid. This function will not follow symbolic links.27os.link(src, dst) 
Create a hard link pointing to src named dst.28os.listdir(path) 
Return a list containing the names of the entries in the directory given by path.29os.lseek(fd, pos, how) 
Set the current position of file descriptor fd to position pos, modified by how.30os.lstat(path) 
Like stat(), but do not follow symbolic links.31os.major(device) 
Extract the device major number from a raw device number.32os.makedev(major, minor) 
Compose a raw device number from the major and minor device numbers.33os.makedirs(path[, mode]) 
Recursive directory creation function.34os.minor(device) 
Extract the device minor number from a raw device number .35os.mkdir(path[, mode]) 
Create a directory named path with numeric mode mode.36os.mkfifo(path[, mode]) 
Create a FIFO (a named pipe) named path with numeric mode mode. The default mode is 0666 (octal).37os.mknod(filename[, mode=0600, device]) 
Create a filesystem node (file, device special file or named pipe) named filename.38os.open(file, flags[, mode]) 
Open the file file and set various flags according to flags and possibly its mode according to mode.39os.openpty() 
Open a new pseudo-terminal pair. Return a pair of file descriptors (master, slave) for the pty and the tty, respectively.40os.pathconf(path, name) 
Return system configuration information relevant to a named file.41os.pipe() 
Create a pipe. Return a pair of file descriptors (r, w) usable for reading and writing, respectively.42os.popen(command[, mode[, bufsize]]) 
Open a pipe to or from command.43os.read(fd, n) 
Read at most n bytes from file descriptor fd. Return a string containing the bytes read. If the end of the file referred to by fd has been reached, an empty string is returned.44os.readlink(path) 
Return a string representing the path to which the symbolic link points.45os.remove(path) 
Remove the file path.46os.removedirs(path) 
Remove directories recursively.47os.rename(src, dst) 
Rename the file or directory src to dst.48os.renames(old, new) 
Recursive directory or file renaming function.49os.rmdir(path) 
Remove the directory path50os.stat(path) 
Perform a stat system call on the given path.51os.stat_float_times([newvalue]) 
Determine whether stat_result represents time stamps as float objects.52os.statvfs(path) 
Perform a statvfs system call on the given path.53os.symlink(src, dst) 
Create a symbolic link pointing to src named dst.54os.tcgetpgrp(fd) 
Return the process group associated with the terminal given by fd (an open file descriptor as returned by open()).55os.tcsetpgrp(fd, pg) 
Set the process group associated with the terminal given by fd (an open file descriptor as returned by open()) to pg.56os.tempnam([dir[, prefix]]) 
Return a unique path name that is reasonable for creating a temporary file.57os.tmpfile() 
Return a new file object opened in update mode (w+b).58os.tmpnam() 
Return a unique path name that is reasonable for creating a temporary file.59os.ttyname(fd) 
Return a string which specifies the terminal device associated with file descriptor fd. If fd is not associated with a terminal device, an exception is raised.60os.unlink(path) 
Remove the file path.61os.utime(path, times) 
Set the access and modified times of the file specified by path.62os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]]) 
Generate the file names in a directory tree by walking the tree either top-down or bottom-up.63os.write(fd, str) 
Write the string str to file descriptor fd. Return the number of bytes actually written.
	
				
		
原创粉丝点击