def __virtual__(): """ Only work on Mac OS ''' if __grains__.get('os') in ['MacOS', 'Darwin']: return __virtualname__ return (False, "Only available on Mac OS systems") def list_(path, **kwargs): """ List all of the extended attributes on the given file/directory :param str path: The file(s) to get attributes from :param bool hex: Return the values with forced hexadecimal values :return: A dictionary containing extended attributes and values for the
-------------------------------------------------------------------------------- Working with files with open(...) as f: var = open('FileName.txt','x') --> x is the opening paramiter r; read only, r+; reading and writing (cursor at begenning), w; writing, w+; reading and writing (will make new file), a; appending (cursor at end) a+; appending and reading (c at end), b; binary add to each one to open in binary edit mode f = open('filename.txt','r').read() --> reads the file and sets it to var f f.close() --> closes the open file f.flush() -> flush internal buffer f.isatty() --> true if file is connected to a tty(-like) device next(f) --> returns next line from the file each time it is called f.read([count]) --> reads entire file: number of bytes to be read from the begenning of file (optional) f.readline(size) reads one line from the file f.readlines(sizehint) --> reads until EOF, returns list containing the lines, size is bytes to read f.write(string) --> writes the sting to the file var f.truncate(size) -> truncated to at most that size f.writelines(sequence) --> writes sequence of strings to file, any iterable object (list of strings) f.closed (true if closed) f.mode (access mode openend) f.name --> file name f.tell() --> tells current position within file (bytes from begenning) f.seek(offset, from) --> offset tells how many bytes, from is refrence pos (0 beg, 1 is current, 2 end) f.count(x) --> counts c in f iterable open(file,'r').close() --> create a new file 'file' and close it from collections import Counter
The API read4 reads 4 consecutive characters from the file, then writes those characters into the buffer array buf. The return value is the number of actual characters read. Note that read4() has its own file pointer, much like FILE *fp in C. Definition of read4: Parameter: char[] buf Returns: int Note: buf[] is destination not source, the results from read4 will be copied to buf[] Below is a high level example of how read4 works: File file("abcdefghijk"); // File is "abcdefghijk", initially file pointer (fp) points to 'a' char[] buf = new char[4]; // Create buffer with enough space to store characters read4(buf); // read4 returns 4. Now buf = "abcd", fp points to 'e' read4(buf); // read4 returns 4. Now buf = "efgh", fp points to 'i' read4(buf); // read4 returns 3. Now buf = "ijk", fp points to end of file Method read: By using the read4 method, implement the method read that reads n characters from the file and store it in the buffer array buf. Consider that you cannot manipulate the file directly. The return value is the number of actual characters read. Definition of read: Parameters: char[] buf, int n
# This method reads a file till the newline, including the newline character. >>> f.readline() 'This is my first file\n' >>> f.readline() 'This file\n' >>> f.readline() 'contains three lines\n' >>> f.readline() '' Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading method return empty values when end of file (EOF) is reached. >>> f.readlines() ['This is my first file\n', 'This file\n', 'contains three lines\n'] """**********************************************************""" Python File Methods: ******************** There are various methods available with the file object. Some of them have been used in above examples. Here is the complete list of methods in text mode with a brief description. Python File Methods: ******************** Method Description close() Close an open file. It has no effect if the file is already closed.
Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> >>> help(open) Help on built-in function open in module __builtin__: open(...) open(name[, mode[, buffering]]) -> file object Open a file using the file() type, returns a file object. This is the preferred way to open a file. See file.__doc__ for further information. >>> open(r'D:\vaibhav passbook\IMAGE5.jpg') <open file 'D:\vaibhav passbook\IMAGE5.jpg', mode 'r' at 0x0275A440> >>> file_new = open(r'D:\vaibhav passbook\IMAGE5.jpg') >>> file_new.name 'D:\\vaibhav passbook\\IMAGE5.jpg' >>> file_new. SyntaxError: invalid syntax >>> file_new.close <built-in method close of file object at 0x0275A180> >>> file_new <open file 'D:\vaibhav passbook\IMAGE5.jpg', mode 'r' at 0x0275A180> >>> file_new.read <built-in method read of file object at 0x0275A180> >>> help(file_new.read) Help on built-in function read: read(...) read([size]) -> read at most size bytes, returned as a string.
remaining lines of the entire file. All these reading method return empty values when end of file(EOF) is reached. >> > f.readlines() ['This is my first file\n', 'This file\n', 'contains three lines\n'] """**********************************************************""" Python File Methods: ** ** ** ** ** ** ** ** ** ** There are various methods available with the file object.
.py [command]\nFor a list of commands and what they do, enter the following:\n./ accounts.py -?" exit() # Information given from -? command if sys.argv[1] == "-?": print "This program allows for viewing account info and history as well as adding\ntransactions.\nThe program reads data from the file assigned to the v ariable ACCT_LIST.\nThe following is a list of commands that can be used:\n-i - h -t\n-i -- Account info\nDisplays the number, holder's name, and balance of th e chosen account.\n-h -- History\nDisplays all transactions for the chosen accou nt in chronological order.\n-t -- Insert transaction\nWithdraw from or deposit t o an account, or create a new account." exit() # Get input file, give meaningful error message in case of failure. try: infile = file(os.environ['ACCT_LIST']) except KeyError: print "Error: No input file assigned to variable ACCT_LIST" exit() # Create data structures to use later transaction_list = [] account_list = [] account_dict = {} # Make the transaction list for line in infile: transaction_data = line.split(':') transaction_list.append(transaction_data) # Make the account list for element in transaction_list: account_list.append(element[1] + " " + element[0]) # Make the sorted account set
231...27 f2.txt 445...45 f3.txt 을 볼수있고 f2 를 클릭하면 link 를 볼수있다 이 링크가 가르키는 file 은 y, z 를 저장하고 있다 commit 에는 주요한 정보 두가지가 있다 1. 이전 commit (parent) 1. commit 이 일어난 시점의 working directory 에있는 file 의 이름 f1.txt 과 이 file 의 content 를 담고있는 file 의 link 정보를 담고있다 각각의 version 마다 서로 다른 tree 를 가르키고 있다 이 tree 에는 file name(f1.txt) file 에 담겨있는 contents 를 담고있는 object 가 link 되어있다 따라서, version 에 적혀있는 tree 를 통해서 version 이 만들어진 시점의 working directory 에 대한 상태를 explore 할수있다 In other words, 각각의 version 으로 snapshot 을 만들고 이것들을 tree data structure 를 통해서 가지고 있다 # ====================================================================== objects 안에 들어가는 file(object) 은 크게 3가지이다 blob object : contents of file 을 저장한다 tree object : 34..22 f1.txt 92..93 f2.txt 34..22 f3.txt commit object : commit 에 대한 정보를 담고있는 object # ====================================================================== @ 지옥에서 온 GIT : 원리 - status의 원리 # ====================================================================== in a folder where there is nothing on the stage, when you execute git status, you will see the following message "nothing to commit, working directory clean" git 은 어떻게 nothing to commit 인지 알게되는지 알아보자
ret = salt.utils.mac_utils.execute_return_result(cmd) except CommandExecutionError as exc: if "No such file" in exc.strerror: raise CommandExecutionError("File not found: {0}".format(path)) if "No such xattr" in exc.strerror: raise CommandExecutionError("Attribute not found: {0}".format(attribute)) raise CommandExecutionError("Unknown Error: {0}".format(exc.strerror)) return ret def write(path, attribute, value, **kwargs): """ Causes the given attribute name to be assigned the given value :param str path: The file(s) to get attributes from :param str attribute: The attribute name to be written to the file/directory :param str value: The value to assign to the given attribute :param bool hex: Set the values with forced hexadecimal values :return: True if successful, otherwise False :rtype: bool :raises: CommandExecutionError on file not found or any other unknown error CLI Example: .. code-block:: bash
Counting Lines in a File - Open a file read-only - Use a for loop to read each line - Count the lines and print out the number of lines fhand = open('mbox.txt') # default is read count = 0 for line in fhand: count = count + 1 # or count += 1 print 'Line Count:', count Reading the *Whole* File - We can read the whole file (newlines and all) into a single string fhand = open('mbox-short.txt') inp = fhand.read() print len(inp) print inp[:20] #=> From stephan.marquar --> first 20 chars (0-19) Searching Through a File - We can put an if statement in our for loop to only print lines that meet some criteria fhand = open('mbox-short.txt') for line in fhand: if line.startswith('From'): #=> .startwith = string utility function print line