This article mainly introduces how to format and compress Python JS files. the example analyzes the Python formatting skills and provides some reference value, for more information about how to format and compress JavaScript files in Python, see the following example. Share
A question not published (I solve it if I write) in 2017.3.20I just wanted to publish it-stackoverflow, but I solved it.1.Platform:windows 8I ' m just trying to modify a file in Python 2.7, which are not in plain text(like. txt,. csv) but docx format,in order to add one or more bytes toIt.However, when I tried to read it through commands:With open (' Ggg.docx ', ' rb+ ') as F:Contents = F.read () # Type (co
Python -- code encoding format conversionLet's talk about the encoding problem first. In the above example, the database in data center B is all GBK encoded, so the data retrieved from the database is GBK, the data retrieved from the database is encoded in GBK format. It must be displayed without garbled characters. If the data retrieved from the database is not
What is JSON:JSON (JavaScript Object Notation) is a lightweight data interchange format. Easy for people to read and write. It is also easy for machine parsing and generation. It is based on JavaScript programming Language, Standard ECMA-262 a subset of 3rd Edition-december 1999. JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #,
Using the Format function for formatting strings in PythonSince python2.6, a new function Str.format () that formats the string has been added to the power. So, what's the advantage of being compared to the previous% format string?GrammarIt replaces% with {} and:.Map sampleThere are 4 ways to implement a value mappingThe first type: where to use1>>>Print('{0},{1}'. Form
All the rules that are included are described firstCurly brace Declaration {}: parameter reference declaration before rendering, curly brackets can be used to denote the ordinal number of the reference parameter, or the variable name is directly referenced. The variable name introduced from the format parameter colon: The number of character bits declares the declaration of a blank auto-fill character declaration of a variable-type declaration: string
Example:1 #-*-coding=utf-8-*-2 __author__='Zhongtang'3 4 5 Import Time6strtime1='20160518010101'7Strtime2='20160518020101'8 9 #string becomes time data structureTenLocaltime1=time.strptime (Strtime1,'%y%m%d%h%m%s') OneLocaltime2=time.strptime (Strtime2,'%y%m%d%h%m%s') A - Printtype (localtime1), localtime1 - Printtype (localtime2), localtime2 the - - #convert from time data structure to timestamp -time1=time.mktime (localtime1) +Time2=time.mktime (localtime2) - + Printtype (time1), time1 A P
Python reads and writes CSV format files
In data analysis, it is often necessary to access data from CSV-formatted files and to write data to a CSV file. It is convenient and easy to read the data in the CSV file directly as Dict type and dataframe, and the following code takes the iris data as an example.
CSV file read as Dict
Code
#-*-Coding:utf-8-*-import csvwith open (' e:/iris.csv ') as Csvfile:reader
The example described in this article is a method for Python to process a text file and generate a specified format file, which implements the following function code as follows:
Import Osimport sysimport string# opens the specified file in the specified mode, gets the file handle def getfileins (Filepath,model): Print ("Open file") print (FilePath) Print (model) return open (Filepath,model) #获取需要处理的文件def
This article describes how to convert python time integer to standard format. For more information, see
The code is as follows:
Import OSImport sysImport pickleImport stringImport reImport timeFrom datetime import dateFrom csv_timestamp_datetime import * Ip_region_list = pickle. load (open ('IP _ region_list.pickle', 'r '))Ip_region_list.sort (key = lambda x: x [0])List_len = len (ip_region_list)Def find
#-*-coding:utf-8-*-#===============================================================================# in Folder# 1, total number of statistical documents# 2. Count the number of files in various formats# 3, log output#===============================================================================Import Os,time,sysDef getprettytime ():Return Time.strftime ('%y-%m-%d%h:%m:%s ', Time.localtime ())def log (content):f = open (' Log.txt ', ' aw+ ')F.write (' F.write (content + ' \ n ')F.close ()def run
Print (' I tested%d '%20 'msg='---------info of%s-----------name:%sage:%d #字符串不能放到%d job:%ssalary:%fyou'll be retired at%s years #数字可以放到%s---------end---------------" % ('Tom','Tom', 'it ', 3444.44,()print(msg) Python If you want to output the contents of the original format, you can add "'", placeholder usage
As an example,>>> u‘\u6ce8\u91ca‘>>> su‘\u6ce8\u91ca‘>>> print s注释>>> print‘unicode‘>>>> print s.encode(‘gbk‘)注释The string pre-plus U is expressed as Unicode encoding, and the Unicode encoding of the current text can be set,For example, the Utf-8 code is the first line plus:# -*- coding: utf-8 -*-And the GBK code is# -*- coding: gbk -*-ReferencePython Chinese encodingDetailed Python-encoded contentAs an example#输出‘\xce\xd2\xca\xc7\xd6\xd0\xce\xc4′can
print generator itself will display generator instead of listL = [i forIinchRange (1,11,2)]#outside is [] is a list#Space change time, memory consumption is large, but no longer CPU#list It is to put all the elements in the memory, here will apply for 5 memory spacePrint(l)#[1, 3, 5, 7, 9]L1 = (i forIinchRange (1,11,2))#outside is () the word is generator#The Generator generator saves memory than the list, it is the time of each loop, it calculates an element according to the rule, and puts it
%y Two-digit year representation (00-99)%Y Four-digit year representation (000-9999)%m Month (01-12)One day in%d months (0-31)%H 24-hour hours (0-23)%I 12-hour hours (01-12)%M minutes (00=59)%s seconds (00-59)%a Local Simplified Week name%A Local Full week name%b a locally simplified month name%B Local Full month name%c Local corresponding date representation and time representation%j Day of the Year (001-366)%p the equivalent of a local a.m. or p.m.%u weeks of the year (00-53) Sunday is the b
The example described in this article is a method for Python to process a text file and generate a specified format file, as shown in the following functional code:
Import OS import sys import string #以指定模式打开指定文件 get file handle def getfileins (Filepath,model): print (open file) print (FilePath) Print (model) return-open (Filepath,model) #获取需要处理的文件 def getprocfile (path): Return Os.listdir (Path) #判断
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.