-
以分隔符分隔的文本文件_将固定宽度/定界符分隔的文本文件内容(输入文件)转换为另一个格式的文本文件...
2020-07-21 15:55:31以分隔符分隔的文本文件Definitions: 定义: Source System The IT system that provide the original data. Targeted System The IT system that will received the output data from Source ....以分隔符分隔的文本文件
Definitions:
定义:
Source System The IT system that provide the original data. Targeted System The IT system that will received the output data from Source System. Input File Referring to the original data file that generated from the Source System. Output File Referring to the formatted Input File. Source File Referring to the Final Data File that will being used by the Targeted System. File Convertor The program that converts the Input File to Output File. Template File The configuration file that defines the rules how the Output File should be generated via the File Convertor. Admin Executables / Template File Generator The program that defines the configuration rules how the Output File should be generated via the File Convertor. 源系统
提供原始数据的IT系统。
目标系统
将从源系统接收输出数据的IT系统。
输入文件
引用从源系统生成的原始数据文件。
输出文件
参考格式化的输入文件。
源文件
引用目标系统将要使用的最终数据文件。
文件转换器
将输入文件转换为输出文件的程序。
模板文件
定义规则的配置文件,该规则应如何通过文件转换器生成输出文件。
管理员可执行文件/模板文件生成器
定义配置规则的程序应如何通过文件转换器生成输出文件。
The Issue
问题
Relating to this file transfer protocol, there are a few issues that need to be agreed on, especially to do with how the data is being transferred.
关于此文件传输协议,需要商定一些问题,尤其是与如何传输数据有关。
There are a few options available:
有一些可用的选项:
- Database to Database Integration Services - Data are being transferred seamlessly between Source System and Targeted System with authenticated credentials
数据库到数据库集成服务-数据通过身份验证在源系统和目标系统之间无缝传输
- Data File Transfer - Data is first exported from the Source System as a file and then imported into the Target System
数据文件传输-数据首先从源系统作为文件导出,然后导入目标系统
- Manual System Entries - Data is recreated manually via some sort of user interface in the Targeted System 手动系统条目-通过目标系统中的某种用户界面手动重新创建数据
What we will focus on in this article is the second scenario, Data File Transfer.
我们将在本文中重点介绍第二种情况,即数据文件传输 。
A common problem is there is no option available in the Source System to directly generate the Source File needed by Targeted System.
一个常见的问题是,源系统中没有可用的选项来直接生成目标系统所需的源文件。
Hence, the Source File (Input File) needs to be further processed before it (Output File) can be recognized and used by the Targeted System.
因此,在目标系统可以识别和使用源文件(输入文件)之前,需要对其进行进一步处理。
Proposed Resolution
拟议决议
1. File Formats
1.文件格式
To ensure the data to be transferred successfully from the Source System to Targeted System, first we need to determine the file format of Input File.
为了确保将数据成功地从源系统传输到目标系统,首先我们需要确定输入文件的文件格式。
First of all, we need to determine what are the sections available in the Input File, most of the cases, there could be a Header section, a Detail section, with an optional Footer section. Each of the sections could be defined differently with different fixed width to define the data that being stored.
首先,我们需要确定输入文件中可用的部分,在大多数情况下,可能会有一个Header部分,Detail部分以及一个可选的Footer部分。 可以用不同的固定宽度不同地定义每个部分,以定义要存储的数据。
Similarly for the Output File, there could have a different format which come with a Header section, a Detail section or even with a Footer section, that's all depends on the Targeted System's requirement on what data format are accepted.
类似地,对于输出文件,页眉节,详细节甚至页脚节可能具有不同的格式,这完全取决于目标系统对接受哪种数据格式的要求。
The difference could be in term of:
区别可能在于:
i) Number of fields required
i)必填字段数
ii) The sequence of fields
ii)字段顺序
iii) The conversion of values
iii)价值转换
iv) The change of fixed width / delimiter
iv)固定宽度/定界符的变化
v) The conversion from fixed width to delimiter-separated, or vice versa
v)从固定宽度到定界符分隔的转换,反之亦然
vi) The use of Derived fields
vi)派生字段的使用
And hence, an Input & Output File Mapping documentation is useful to document all the requirements.
因此,输入和输出文件映射文档对于记录所有需求很有用。
2. File Converter
2.文件 转换器
A few things to consider:
需要考虑的几件事:
i) User interface consideration
i)用户界面注意事项
Do we need to build an User Interface to enable user to operate the program or we simply make it as simple as a Console Program or a Service that running at background?
我们是否需要构建一个用户界面以使用户能够运行该程序,还是仅仅使其像在后台运行的控制台程序或服务一样简单?
ii) Programming Languages and Tools
ii)编程语言和工具
What programming languages or tools to be used to generated the Output File?
哪些编程语言或工具可用于生成输出文件?
There are few options available, such as:
可用的选项很少,例如:
a) SQL Server Integration Services (SSIS)
a)SQL Server集成服务(SSIS)
We can create a Script Task (in C# or VB.NET) and write the logic within.
我们可以创建一个脚本任务(在C#或VB.NET中)并在其中编写逻辑。
b) a Compiled Executables, VB Script, PowerShell script etc
b)编译的可执行文件,VB脚本,PowerShell脚本等
Depends on the efficiency and convenience of developer, different programming languages and tools could be used to develop the File Convertor
根据开发人员的效率和便利性,可以使用不同的编程语言和工具来开发文件转换器。
iii) Delimiter and Text Qualifier
iii)分隔符和文本限定符
In case the Delimiter was being used in either Input File or Output File, do consider to use the Delimiter as unique as possible, which is different from the data content.
如果在输入文件或输出文件中使用了定界符,请考虑尽可能使用定界符,这与数据内容不同。
A Text Qualifier could be very useful to use in case inevitably the data also contains the character of delimiter as part of the content.
如果数据不可避免地包含定界符字符作为内容的一部分,则使用文本限定符可能非常有用。
iv) Other Consideration
iv)其他考虑
Other than that, we may think what features we should build into the File Converter, such as:
除此之外,我们可能会考虑应该在文件转换器中内置哪些功能,例如:
a) Data verification
a)数据验证
To verify the data checksum, size, format, etc.
验证数据校验和,大小,格式等
b) Derived fields
b)派生字段
To enable the File Converter to have capability to generate derived fields based on certain logic, such as summation of fields, count of records, etc.
使文件转换器能够基于某些逻辑(例如字段总和,记录计数等)生成派生字段。
3. Static or Dynamic Approach?
3.静态还是动态方法?
As what we can see from Figure in section: 1. File Formats above, it illustrates the Static mapping of Input File to Output File.
正如我们在以下部分的图中所看到的:1.上面的文件格式,它说明了输入文件到输出文件的静态映射。
The question that may arise is how can have a more dynamic approach to make it possible for the File Convertor to generate different Output File with different output formats?
可能出现的问题是,如何有一种更动态的方法来使文件转换器生成具有不同输出格式的不同输出文件?
In real programming world, it's really not a practical approach to hard code the logic in the codes. Therefore if there's a chance, the developers will try to make things to be configurable as possible as it can.
在实际的编程世界中,将代码中的逻辑硬编码实际上不是一种实用的方法。 因此,如果有机会,开发人员将尝试使事情尽可能地可配置。
I think to make this possible, we would need to have another Admin Executables (aka Template File Generator) in order to generate a Template File (we may also called it as a profile), so that when the File Converter starts to convert the Input File's content, it would actually read the configuration rules in the Template File and then do the conversion accordingly to generate the Output File.
我认为要使其成为可能,我们将需要另一个Admin Executables(又名模板文件生成器)才能生成模板文件(我们也可以将其称为配置文件),以便在文件转换器开始转换输入时文件的内容,它将实际读取模板文件中的配置规则,然后进行相应的转换以生成输出文件。
How can this Template File looks like?
该模板文件的外观如何?
Well, it depends on what programming languages and tools we are using. As a general guideline, it probably will be in file format such as XML or Config file.
好吧,这取决于我们使用的编程语言和工具。 作为一般准则,它可能采用XML或Config文件之类的文件格式。
Sample using XML:
使用XML的示例:
<?xml version="1.0"?> <setting> <ver>1.0</ver> <input> <format>fixed width</format> <header> <code>header</code> <isdetail>false</isdetail> <field> <code>1</code> <name>Record Identifier</name> <type>Char</type> <size>34</size> <start>1</start> <end>34</end> <remarks></remarks> </field> </header> <header> <code>detail</code> <isdetail>true</isdetail> <field> <code>SubmitDate</code> <name>Submission Date</name> <type>Date</type> <format>YYYYMMDD</format> <size>8</size> <start>1</start> <end>8</end> <remarks></remarks> </field> <field> <code>SerialNo</code> <name>Serial Number</name> <type>Numeric</type> <size>9</size> <start>9</start> <end>17</end> <remarks></remarks> </field> <field> <code>CustName</code> <name>Customer Name</name> <type>Char</type> <size>20</size> <start>18</start> <end>37</end> <remarks></remarks> </field> </header> </input> <output> <format>fixed width</format> <header> <code>AcctList</code> <remarks>This is the Account List</remarks> <printremarks>false</printremarks> <isdetail>true</isdetail> <field> <code>SubmitDate</code> <source> <code>detail|SerialNo</code> </source> <trim>false</trim> <name>Submission Date</name> <type>Date</type> <format>MM/DD/YYYY</format> <size>10</size> <start>1</start> <end>10</end> <align>right</align> <remarks></remarks> </field> <field> <code>AppCode</code> <source> <code>detail|SerialNo</code> </source> <trim>true</trim> <formula></formula> <name>Application Code</name> <type>Numeric</type> <size>9</size> <start>11</start> <end>19</end> <align>left</align> <remarks></remarks> </field> </header> <header> <code>AcctTotal</code> <remarks>This is the Account Total</remarks> <printremarks>true</printremarks> <isdetail>false</isdetail> <field> <code>AppCode</code> <source> <code>detail|SerialNo2</code> </source> <trim>true</trim> <formula>{SUM}(1)</formula> <name>Total Application</name> <type>Numeric</type> <format>#,#0</format> <size>7</size> <start>1</start> <end>7</end> <align>right</align> <remarks></remarks> </field> </header> </output> </setting>
To give a sample to reading above template using C# codes, we can customize this sample:
为了提供使用C#代码阅读上述模板的示例,我们可以自定义此示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.IO; namespace MyFileConvertor { class FileConvertor { private XmlDocument doc; public String TemplateFileVersion { get; set; } public Input Input { get; set; } public Output Output { get; set; } public FileConvertor(String TemplatePath) { doc = new XmlDocument(); Input = new Input(); Output = new Output(); doc.Load(TemplatePath); TemplateFileVersion = doc.SelectSingleNode("setting/ver").InnerText; Input.Format = doc.SelectSingleNode("setting/input/format").InnerText; XmlNodeList inputHeaders = doc.SelectNodes("setting/input/header"); foreach (XmlNode inputHeader in inputHeaders) { InputHeader hdr = new InputHeader(); hdr.Code = inputHeader.SelectSingleNode("code").InnerText; hdr.isDetail = inputHeader.SelectSingleNode("isdetail").InnerText == "true" ? true : false; XmlNodeList inputFields = inputHeader.SelectNodes("field"); foreach (XmlNode inputField in inputFields) { Field fld = new Field(); fld.Code = inputField.SelectSingleNode("code").InnerText; fld.Name = inputField.SelectSingleNode("name").InnerText; fld.Type = inputField.SelectSingleNode("type").InnerText; fld.Format = getNodeText(inputField.SelectSingleNode("format")); fld.Size = Convert.ToInt32(inputField.SelectSingleNode("size").InnerText); fld.Start = Convert.ToInt32(inputField.SelectSingleNode("start").InnerText); fld.End = Convert.ToInt32(inputField.SelectSingleNode("end").InnerText); fld.Remarks = inputField.SelectSingleNode("remarks").InnerText; hdr.Fields.Add(fld); } Input.InputHeaders.Add(hdr); } Output.Format = doc.SelectSingleNode("setting/output/format").InnerText; XmlNodeList outputHeaders = doc.SelectNodes("setting/output/header"); foreach (XmlNode outputHeader in outputHeaders) { OutputHeader hdr = new OutputHeader(); hdr.Code = outputHeader.SelectSingleNode("code").InnerText; hdr.Remarks = outputHeader.SelectSingleNode("remarks").InnerText; hdr.PrintRemarks = outputHeader.SelectSingleNode("printremarks").InnerText; hdr.isDetail = outputHeader.SelectSingleNode("isdetail").InnerText == "true" ? true : false; XmlNodeList outputFields = outputHeader.SelectNodes("field"); foreach (XmlNode outputField in outputFields) { Field fld = new Field(); fld.Code = outputField.SelectSingleNode("code").InnerText; fld.Name = outputField.SelectSingleNode("name").InnerText; fld.Type = outputField.SelectSingleNode("type").InnerText; fld.Format = getNodeText(outputField.SelectSingleNode("format")); fld.Size = Convert.ToInt32(outputField.SelectSingleNode("size").InnerText); fld.Start = Convert.ToInt32(outputField.SelectSingleNode("start").InnerText); fld.End = Convert.ToInt32(outputField.SelectSingleNode("end").InnerText); fld.Alignment = outputField.SelectSingleNode("align").InnerText; fld.Remarks = outputField.SelectSingleNode("remarks").InnerText; fld.Formula = getNodeText(outputField.SelectSingleNode("formula")); fld.IsTrim = getNodeText(outputField.SelectSingleNode("trim")) == "true" ? true : false; XmlNodeList outputFieldCodes = outputField.SelectNodes("source"); foreach (XmlNode outputFieldCode in outputFieldCodes) { Source src = new Source(); src.Codes.Add(outputFieldCode.SelectSingleNode("code").InnerText); fld.Sources.Add(src); } hdr.Fields.Add(fld); } Output.OutputHeaders.Add(hdr); } } public String getNodeText(XmlNode node) { try { return node.InnerText; } catch (Exception) { return ""; } } public String getNodeText(XmlNode node, String defaultReturn) { try { return node.InnerText; } catch (Exception) { return defaultReturn; } } } class Input { public String Format { get; set; } public List<InputHeader> InputHeaders; public Input() { InputHeaders = new List<InputHeader>(); } } class InputHeader { public String Code { get; set; } public Boolean isDetail { get; set; } public List<Field> Fields; public InputHeader() { Fields = new List<Field>(); } } class Output { public String Format { get; set; } public List<OutputHeader> OutputHeaders; public Output() { OutputHeaders = new List<OutputHeader>(); } } class OutputHeader { public String Code { get; set; } public String Remarks { get; set; } public String PrintRemarks { get; set; } public Boolean isDetail { get; set; } public List<Field> Fields; public OutputHeader() { Fields = new List<Field>(); } } class Field { public String Code { get; set; } public Boolean IsTrim { get; set; } public String Formula { get; set; } public String Name { get; set; } public String Type { get; set; } public String Format { get; set; } public int Size { get; set; } public int Start { get; set; } public int End { get; set; } public String Alignment { get; set; } public String Remarks { get; set; } public List<Source> Sources; public Field() { Sources = new List<Source>(); } } class Source { public List<String> Codes; public Source() { Codes = new List<string>(); } } }
In general, we can build a much more complex rules in the Template File to meet the requirements.
通常,我们可以在模板文件中构建更复杂的规则来满足要求。
So, the preferred Programming Languages and Tools will play a crucial role to read the settings from the Template File, which eventually based on the logic within to generate the Output File.
因此,首选的编程语言和工具将扮演至关重要的角色,以从模板文件中读取设置,而模板文件最终将基于其中的逻辑来生成输出文件。
This may not be an easy task but it's worth a try :)
这可能不是一件容易的事,但是值得一试:)
Conclusion:
结论:
As a whole, we need to ensure the data accuracy and integrity are take into consideration.
总体而言,我们需要确保考虑到数据的准确性和完整性。
Some of other concerns:
其他一些问题:
1. We can build an application log to track the activities of during the file conversion process.
1.我们可以构建一个应用程序日志来跟踪文件转换过程中的活动。
2. We can embed the security algorithms to protect our data if necessary.
2.如果需要,我们可以嵌入安全算法来保护我们的数据。
3. Automate the whole process by integrate it as part of the ETL (Extract, Transform and Load) or Windows Scheduled Task process.
3.通过将其集成为ETL(提取,转换和加载)或Windows计划任务过程的一部分来自动化整个过程。
4. How the Template File to be updated/ stored if the File Converter had been deployed to many computer machines?
4.如果文件转换器已部署到许多计算机上,如何更新/存储模板文件?
More references:更多参考:Script Task
脚本任务
https://docs.microsoft.com/en-us/sql/integration-services/control-flow/script-task
https://docs.microsoft.com/zh-cn/sql/integration-services/control-flow/script-task
Text Import Wizard
文字汇入精灵
https://support.office.com/en-us/article/Text-Import-Wizard-c5b02af6-fda1-4440-899f-f78bafe41857?ui=en-US&rs=en-US&ad=US&fromAR=1
https://support.office.com/zh-CN/article/Text-Import-Wizard-c5b02af6-fda1-4440-899f-f78bafe41857?ui=zh-CN&rs=zh-CN&ad=US&fromAR=1
(Read Step 2 of 3 for explanation of Delimiter and Text Qualifier)
(阅读第2步(共3步)以了解分隔符和文本限定符)
以分隔符分隔的文本文件
- Database to Database Integration Services - Data are being transferred seamlessly between Source System and Targeted System with authenticated credentials
-
VC读写指定分隔符的UNICODE文本文件
2012-10-24 16:55:51Unicode文本文件以0xff、0xfe两个字节开头,后面是Unicode文本内容。在创建文件的时候先向文件写入0xff、0xfe两个字节,然后再写入Unicode字符串即可;在读文件的时候,先读出前两字节,然后将后面数据直接读入...本例中文本间用“,”作为分隔符,在UNICODE下,原本用空格作为分隔符,发现貌似行不通哦~
问题:
Unicode文本文件以0xff、0xfe两个字节开头,后面是Unicode文本内容。在创建文件的时候先向文件写入0xff、0xfe两个字节,然后再写入Unicode字符串即可;在读文件的时候,先读出前两字节,然后将后面数据直接读入Unicode字符串缓冲区。至于二进制文件,直接把要写的数据写入文件即可。
网上其他方法:
一.UNICODE下写ANSI编码的文本
//小例子
str=_T("你好"); char szANSIString[MAX_PATH]; WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,str,-1,szANSIString,sizeof(szANSIString),NULL,NULL); file.Write(szANSIString,4);
二.
//写文件
CString strFileName=strCurProjFullPath+_T("\\")+_T("OilType.dat"); CFile file(strFileName,CFile::modeCreate|CFile::modeWrite|FILE_FLAG_NO_BUFFERING); //指明存储为Unicode格式 const unsigned char LeadBytes[] = {0xff, 0xfe};//网上有说是BOM头,尚未查阅先关资料 file.Write(LeadBytes, sizeof(LeadBytes)); for (iRows=0;iRows<iUsefulRowsCount;iRows++) { for (iCols=0;iCols<iClosCount;iCols++) { pCurrentCell=m_pGridCtrl->GetCell(iRows,iCols); strCurCellTxt=pCurrentCell->GetText(); file.Write(strCurCellTxt,wcslen(strCurCellTxt)*sizeof(wchar_t)); if ((iClosCount-iCols) != 1) { file.Write(_T(","),wcslen(_T(","))*sizeof(wchar_t));//用逗号作为分隔符 } } file.Write(_T("\r\n"),wcslen(_T("\r\n"))*sizeof(wchar_t)); } file.Close(); MessageBox(_T("保存完毕!"),_T("保存"),MB_OK);
///读文件
// CStdioFile stdFile(strFileFullPath,CFile::modeRead); CString fileLineTxt=_T(""); CString cellTxt=_T(""); // Open the file with the specified encoding FILE *fStream; errno_t e = _tfopen_s(&fStream,strFileFullPath, _T("rt,ccs=UNICODE")); if (e != 0) return; // failed..CString sRead; CStdioFile stdFile(fStream); // open the file from this stream CString sRead; int iRowID=-1; while( stdFile.ReadString(fileLineTxt))//每次读取一行内容 { CAtlString str(fileLineTxt); CAtlString resToken; iRowID++; for (int iColID=0,iPos=0;iColID<m_uGridColumnsCount+1;iColID++) { /*CString::Tokenize()碰到连续多个分隔字符是作为一个处理的,AfxExtractSubString()中多个分隔符可区分处理。*/ resToken= str.Tokenize(_T(","),iPos); ASSERT(iPos!=-1); pCell=m_pGridCtrl->GetCell(iRowID,iColID); pCell->SetText(resToken); } } stdFile.Close();
-
R:从带分隔符的文本文件导入数据
2014-10-27 13:35:15可以使用read.table()从带分隔符的文本文件中导入数据。此函数可读入一个表格格式的文件并将其保存为一个数据框。其语法如下: Mytable 其中,file是一个带分隔符的ASCII文本文件,header是一个表明首行是否...可以使用read.table()从带分隔符的文本文件中导入数据。此函数可读入一个表格格式的文件并将其保存为一个数据框。其语法如下:
Mytable <- read.table( filename, header = LogicalValue, sep = "delimiter", row.names = "name" )
其中,file是一个带分隔符的ASCII文本文件,header是一个表明首行是否包含了变量名的逻辑值(TRUE或FALSE),sep用来指定分隔数据的分隔符,rows.names是一个可选参数,用以指定一个或多个表示行标识符的变量。
mytable <- read.table( "D:/RCodes/mytable.csv",header=TRUE,sep=",", row.names="id" )
注:参数sep允许导入那些使用逗号以外的符号来分隔行内数据的文件。你可以使用sep="\t"读取以制表符分隔的文件。此参数的默认值为sep="",即表示分隔符可为一个或多个空格、制表符、换行符或回车符。
从指定位置读入了一个名为mytable.csv的逗号分隔文件,从文件的第一行取得了各变量的名称,将变量id指定为行标识符。最后将结果保存到了名为mytable的数据框中。
默认情况下,字符型变量将转换为引子。我们并不总是希望程序这样做,有很多办法禁止这种转换行为。其中包括设置选项stringsAsFactors=FALSE,这将停止对所有字符型变量的此种转换。另一种方法是使用选项colClasses为每一列指定一个类,例如logical(逻辑型)、numeric(数值型)、character(字符型)、factor(因子)。
函数read.table()还拥有许多微调数据导入方式的追加选项。更多详情,可以参考help(read.table)。
也可以直接使用下面的命令导入.csv格式的文件:
mytable <- read.csv( "D:/RCodes/mytable.csv" )
函数read.table()的格式及参数格式:
read.table(file, header = FALSE, sep = "", quote = "\"'", dec = ".",row.names, col.names, as.is = FALSE, na.strings = "NA",colClasses = NA, nrows = -1,skip = 0, check.names = TRUE, fill = !blank.lines.skip,strip.white = FALSE, blank.lines.skip = TRUE,comment.char = "#")
函数read.table()选项值及说明
选项值
说明
file
文件名(包在""内,或使用一个字符型变量),可能需要全路径
header
一个逻辑值(FALSE或TRUE),用来反映这个文件的第一行是否包含变量名
sep
文件中的字段分离符
quote
指定用于包围字符型数据的字符
dec
用来表示小数点的字符
row.names
保存着行名的向量,或文件中一个变量的序号或名字,缺省时行号取为1,2,3,……
col.names
指定列名的字符向量
as.is
控制是否将字符型变量转化为引子型变量(如果值为FALSE),或者仍将其保留为字符型(TRUE)。As.is可以说逻辑型,数值型或者字符向量,用来判断变量是否被保留为字符
na.strings
代表确实数据的值(转化为NA)
colClasses
指定各列的数据类型的一个字符型向量
nrows
可以读取的最大行数(忽略负值)
skip
在读取数据前跳过的行数
check.names
如果为TRUE,则检查变量名是否在R中有效
fill
如果为TRUE且非所有的行中变量数目相同,则用空白填补
strip.white
在sep已指定的情况下,如果为TRUE,则删除字符型变量前后多余的空格
blank.lines.skip
如果为TRUE,忽略空白行
comment.char
一个字符用来在数据文件中写注释,以这个字符开头的行被忽略
-
Python基于分隔符的文本数据存取
2021-02-13 16:59:42常见的存储文本数据的文本文件主要有两种:一种是基于分隔符的文本数据文件,这里分隔符可以是空格、逗号、单双引号、TAB制表符等,使用分隔符的目的是将同一行数据的不同列(字段)分开,便于以统一的规律读写;...Python基于分隔符的文本数据存取
基于分隔符的文本数据文件以行尾各条数据的分隔,以各种分隔符(同一个文本数据文件中通常只使用一种)作为一条数据内不同列(字段)的分隔,存储需要处理的数据。下面是分别使用TAB制表符、逗号、空格、竖线作为分隔符的四个文本数据文件的例子。
在Python中读写这类文件一般采用三种方法CSV模块、Numpy库、Pandas库。
CSV模块读写
(1)读取
reader()
方法和writer()
方法的delimiter
参数指明了文件使用的分隔符。import csv with open('竖线.txt', encoding='utf-8') as cf: lines = csv.reader(cf, delimiter='|') for line in lines: print(line)
(2)写入
import csv headers = ['姓名', '性别'] rows = [('张三', '男'), ('李四', '男'), ('王五', '男')] with open('test.txt', 'a+', encoding='utf-8', newline="")as fp: wf = csv.writer(fp) wf.writerow(headers) wf.writerows(rows)
Numpy库读写
(1)读取
import numpy as np data = np.loadtxt('竖线.txt', dtype=str, delimiter='|', unpack=False, encoding='utf-8') print(data)
通过结果可以看到,Numpy
库读取的结果和CSV
模块读取的结果不同;Numpy
读取的结果数据类型是ndarry
,与CSV
模块读取得到的list不同。loadtxt()
函数loadtxt(fname, dtype=<class ‘float’>, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding=‘bytes’)
各参数含义如下:
- fname:要读取的带路径的文件名,如文件后缀是.gz或.bz2,泽稳健将被解压,然后再载入。
- dtype:要读取的数据类型。
- comments:文件头部或尾部字符串的开头字符,用于识别头部或尾部字符串。
- delimiter:分隔字段(列)的字符串。
- converters:将某列使用特定函数处理。
- skiprows:跳过前若干行。
- usecols:获取某些列,如需要前三列则为usecols=(0,1,2)。
- unpack:取值为True时,每列数据以数组的形式返回。
- ndmin:指定读取文件后存储数据的数组最少应具有的ndarry维度。
- encoding:解码输入文件的字符集编码。
(2)写入
import numpy as np data = [['姓名', '性别'], ['张三', '男'], ['李四', '男'], ['王五', '男']] np.savetxt('test.txt', data, delimiter=',', newline='\n', fmt='%s, %s')
savetxt()
函数savetxt(fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=’\n’, header=’’, footer=’’, comments=’# ', encoding=None)
各参数含义如下:
- fname:要写入的带路径的文件名。
- X:要存储的移位或二维数组。
- fmt:控制数据存储的格式。
- delimiter:分隔字段(列)的字符串。
- newline:数据行之间的分隔符。
- header:文件头部写入的字符串。
- footer:文件末尾写入的字符串。
- comments:文件头部或者尾部字符串的开头字符串,默认为#。
- encoding:写入文件的字符集编码。
使用pandas库读写
(1)读取
import pandas as pd df = pd.read_csv('竖线.txt', delimiter='|') print(df)
(2)写入import pandas as pd dic = {'姓名': ['张三', '李四', '王五'], '姓别': ['男', '男', '男']} df = pd.DataFrame(dic) df.to_csv('test.txt', index=False)
三种方式的区别
- 读取数据以后得到的数据类型,以及写入文件后的数据格式不同。
- 主要功能和运行效率不同。
CSV
模块主要用于处理文本型数据的读写;而Pandas
和Numpy
的功能比CSV
模块要强大很多,Numpy
库主要用于面向高精度和高性能的计算,提供了大量统计相关的函数;Pandas
库多用于时间序列的分析,可以便捷快速的处理大量连续性数据。
-
mapreduce案例之统计文本文件中单词出现的次数(单词以空格作为分隔符)
2020-01-11 17:55:29需求:mapreduce案例之统计文本文件中单词出现的次数(单词以空格作为分隔符) D盘原始文件如下: WordCountRunner类 WordCountMapper类 WordCountReducer类 启动测试~ 此时会报错!原因是输出路径... -
C++读取文本文件中以TAB作为分隔符,且中间字段有为空的情况的方法?
2014-12-18 17:48:51getline()将testData.txt中的第一行记录读入到一个string中,然后搜索第n个分隔符进行定位,判断第n个字段长度,使用substr,截取该字段,并赋值给目标string。 程序: #include #include using -
模糊寻找文本行子程序,返回以换行符分隔的文本
2017-10-14 19:52:00子程序 模糊寻找文本行子程序, 文本型, 公开, 批量寻找时,返回以换行符分隔的文本 .参数 文件名, 文本型, , 完整的文件路径 .参数 寻找的文本, 文本型 .参数 是否区分大小写, 逻辑型, 可空 .参数 是否批量寻找, ... -
关于带分隔符文件的读取方法
2019-09-23 21:48:33在系统中,经常有批量输入和输出的操作。...今天看了《Core Java2》,发现还可以用Java自带的分隔符读入方法来实现。如下文本: 123 Harry Hacker,35500,1989,10,1 Carl Crecker,75000,1987,12,15 Tony Te... -
python打开csv文件设定分隔符_制表符分隔符在python中编写和打开CSV文件时不起作用...
2021-02-04 01:55:18我试图打开一个CSV文本文件,并以CSV格式将输出写入单独的文件中。我相信我要打开的文件是制表符分隔的CSV文件。但是当我把“\t”同时用于写和打开文件时,我没有得到任何输出,我的代码也不能工作。当我在写和打开... -
awk指定分隔符_Linux文本三剑客 -- awk命令
2021-01-18 12:12:01awk主要用于处理有格式的文本,例如/etc/passwd这种用法awk 选项 'pattern{action}' 文件路径选项-F指定分隔符 -- 如(-F:)工作流程awk -F: '{print $1,$3}' /etc/passwdawk会读取文件的一行内容然后赋值给$0然后awk... -
mysql导出csv 分隔符_导出到CSV文件,CSV文件好像是以逗号为分隔符的吧?如果数据库字段里含有逗号怎么处理...
2021-02-01 00:34:55二、更改分隔符的步骤:通过打开文本62616964757a686964616fe58685e5aeb931333365646263文件来导入文本文件:可以使用“打开”命令将在其他程序中创建的文本文件转换为 Excel 工作簿。1、单击“Microsoft Office ... -
MS-GF + .tsv结果文件或SEQUEST提要文件(或第一个匹配文件)转换为一系列制表符分隔的文本文件,...
2021-02-24 03:55:11Tandem结果文件(XML格式)转换为一系列制表符分隔的文本文件,以汇总结果。 它还支持来自MSAlign,TopPIC,MODa,MODPlus,MSPathFinder的结果文件,以及SEQUEST概要/首次命中文件。 PHRP将在修饰的肽的肽序列中... -
以空格为分隔符读取内容给两个变量_问与答61: 如何将一个文本文件中满足指定条件的内容筛选到另一个文本...
2021-01-13 19:37:23图1现在,我要将以60至69开头的行放置到另一个名为“OutputFile.csv”的文件中。图1中只是给出了少量的示例数据,我的数据有几千行,如何快速对这些数据进行查找并将满足条件的行复制到新文件中?A:VBA代码如下:... -
hive:编写java代码,将文本中的分隔符替换成\001
2020-08-10 14:57:57但是hive表中的分隔符是\001,而查询出的结果是以\t分割,所以需要将\t修改为\001。 思路 1.编写代码,使用jdbc链接数据库,将查询结果以\001分割,并写进文件。 2.在sql-server客户端查询,将结果粘贴进txt文件... -
Hive分隔符
2019-02-13 17:16:53用户应该很熟悉以逗号或者制表符分隔的文本文件,也就是所谓的逗号分隔值(CSV)或者制表符分隔值(TSV)。只要用户需要,Hive是支持这些文件格式的。然而,这两种文件格式有一个共同的缺点,那就是用户需要对文本文件中... -
awk 分隔符 多个空格_awk分隔符设定为多个字符或字符串
2021-01-17 14:23:25awk -F"[0][1]" '{}' 这种形式指定的分隔符是合并的关系,即以“01”作为一个字符为分隔符。故假如有test.txt文本文件只有一行:1. mail from: tomcat@gmail.com 2. subject:hello 3. data:2012-07-12 17:00 4. c... -
awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再进行各种分析处理。
2015-10-19 11:00:08简单来说awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再进行各种分析处理。 awk有3个不同版本: awk、nawk和gawk,未作特别说明,一般指gawk,gawk 是 AWK 的 GNU 版本。 awk其名称得自于它... -
linux命令学习(11)—— awk -F ':',以冒号为分隔符
2018-04-07 17:03:22linux命令学习(11)—— awk -F ':',以冒号为分隔符参考网址:https://www.cnblogs.com/datalife/p/5887715.htmlawk是一个强大的文本分析工具,相对于grep的查找,sed的编辑,awk在其对数据分析并生成报告时,显得尤... -
Linux高级命令—— awk -F ‘:‘,以冒号为分隔符
2020-08-03 19:40:03简单来说awk就是把文件逐行的读入,默认以空格为分隔符将每行切片,切开的部分再进行各种分析处理。 awk是行处理器,相比较屏幕处理的优点,在处理庞大文件时不会出现内存溢出或是处理缓慢的问题,通常用来格式化文本... -
awk指定分隔符_Linux 命令之 awk 用法
2021-01-18 12:10:49概述一个强大的文本分析工具命令,把文件逐行的读入然后执行相应的命令,以空格为默认分隔符将每行切片,切开的部分再进行各种分析处理,通常用来格式化文本文件中的信息.主要涉及的概念有记录(行)、域(列)、域分隔符 1.... -
PDI-KETTLE-4 使用Kettle完成通用DB数据获取生成指定分隔符的文件并通过FTP上传的功能...
2017-10-09 17:32:00在生产环境中,我们经常会遇到数据定时同步的问题,这里整理出一个... 定时从数据库获取时间范围内的数据,然后将数据生成指定格式的文本文件,并将文件上传到指定的FTP服务器上。 二、需要准备什么环境? KET... -
java读取csv文件 逗号_java读取csv文件内容(逗号分隔、回车换行文本)
2021-02-26 12:25:22最近在做项目时需要每日更新大小额支持的银行列表信息,该文件从核心下载,并使用java项目解析放到数据库中,该文件是文本文件,一行为一条记录,记录中以逗号分隔字段,字段以双引号包裹,起初以这种规则自己写一个... -
awk分隔符设定为多个字符或字符串
2015-07-04 22:59:39awk -F"[0][1]" '{}' 这种形式指定的分隔符是合并的关系,即以“01”作为一个字符为分隔符。 故假如有test.txt文本文件只有一行: 1. mail from: tomcat@gmail.com 2. subject:hello 3. data:2012-07-12 -
CSV---逗号分隔符
2020-04-30 15:08:15所谓“CSV”,是Comma Separated Value(逗号分隔值)的英文缩写,通常都是纯文本文件。 通常CSV文件开头是不留空的,以行为单位,每行记录多项数据,每项数据用逗号 来分隔(标准英文逗号)。 如用记事本写下: ...
-
PPT大神之路高清教程
-
华为1+X认证——网络系统建设与运维(初级)
-
湖南大学大一《普通化学》试题及答案.pdf
-
湖南大学《高等数学A1》期末复习知识点总结.pdf
-
用Go语言来写区块链(一)
-
Excel如何将引用的sheet名称全部替换。
-
JQuery 选择器
-
【Pytorch】激活函数与loss的梯度
-
浅谈排序算法分析-推荐博文
-
JavaScript入门(一)
-
湖南大学《线性代数》期末知识点总结.pdf
-
零基础极简以太坊智能合约开发环境搭建并开发部署
-
投标方法论
-
2021-03-02
-
Spring Boot面试讲解
-
PowerBI重要外部工具详解
-
Seata v1.3 使用教程.pdf
-
你好
-
河北工业大学《混凝土结构设计》填空题及答案.pdf
-
朱老师鸿蒙系列课程第1期-3.鸿蒙系统Harmonyos源码配置和管理